# Using ActiveMDX with Next.js

## You need the MDX Loader and Next.js Config

```javascript
// next.config.mjs
import { removeFrontMatter } from "active-mdx/src/plugins/mdx.js"
import nextMdx from "@next/mdx"
import gfm from "remark-gfm"

const withMDX = nextMdx({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [removeFrontMatter, gfm],
    rehypePlugins: []
  }
})

export default withMDX({
  pageExtensions: ["js", "jsx", "md", "mdx"],
  webpack: (config, { isServer }) => {
    // Fixes npm packages (mdx) that depend on `fs` module
    if (!isServer) {
      config.resolve.fallback.fs = false
    }

    return config
  }
})
```

## Defining a collection and models

You should create a server module that exports the collection and specifies the root folder where the mdx content will live

```javascript
// content/index.js
import { Collection } from "active-mdx"
import Epic from "./models/Epic.mjs"
import Story from "./models/Story.mjs"
import Index from "./models/Index.mjs"

import path from "path"

const rootPath = path.parse(import.meta.url.replace("file://", "")).dir

export const collection = new Collection({ rootPath })

collection.model("Index", Index)
collection.model("Epic", Epic)
collection.model("Story", Story)

export { Epic, Story, Index }

export default collection
```

## A CatchAll Page which will display any document in the collection

```javascript
// pages/[...catchAll].js
import content from "content"
import components from "content/mdx"

export default function CatchAllPage({ documentId, doc, model } = {}) {
  const Component = components[documentId] || (() => <div>{documentId}</div>)
  return <Component />
}

export async function getStaticPaths() {
  await content.load()

  const paths = content.available.map((catchAll) => ({
    params: { catchAll: catchAll.split("/") }
  }))

  return {
    paths,
    fallback: false
  }
}

export async function getStaticProps(context = {}) {
  const { params = {} } = context
  await content.load()

  const documentId = params.catchAll.join("/")
  const doc = content.document(documentId)
  const model = doc.toModel()

  return {
    props: {
      documentId,
      model: model.toJSON(),
      doc: JSON.parse(JSON.stringify(doc.toJSON()))
    }
  }
}
```

## Using Next.js API Routes to work with the collection / query models /

```javascript
// pages/api/active-mdx/[...catchAll].js
import NextAPI from "active-mdx/src/next/api.js"
import content from "content"

export default NextAPI(content)
```
