next-contentlayer

The Next.js plugin provides helpers for improving the developer experience in using Contentlayer with Next.js.

withContentlayer

The withContentlayer utility automatically hooks Contentlayer into Next.js build and dev processes, which means you don't have to worry about working with the CLI when running or building your Next.js project.

To enable it, add the following to your next.config.js file:

// next.config.js

import { withContentlayer } from 'next-contentlayer'

export default withContentlayer({})

useMDXComponent

If you're using MDX in your Next.js project, useMDXComponent makes it easy to render MDX in your layouts.

Here is an example of a layout that receives a slug parameter, then uses it to retrieve a document and render MDX on the page.

import { useMDXComponent } from 'next-contentlayer/hooks'
import { allDocs } from 'contentlayer/generated'
import Button from '../components/Button'

const mdxComponents = {
  Button,
}

export default function DocPage({ doc }) {
  const MDXContent = useMDXComponent(doc.body.code)

  return (
    <div>
      <h1>{doc.title}</h1>
      <MDXContent components={mdxComponents} />
    </div>
  )
}

export const getStaticProps = ({ params: { slug } }) => {
  const doc = allDocs.find((doc) => doc._raw.flattenedPath === slug)
  return { props: { doc } }
}

Remember to set contentType: 'mdx' in your config for proper processing of MDX files.

For a more holistic view of using MDX in a project, refer to the example Next.js project.

createContentlayerPlugin

The createContentlayerPlugin function allows you to add non-default configuration options to the next-contentlayer plugin. This is not a common use. See withContentlayer for typical use.

import { createContentlayerPlugin } from 'next-contentlayer'

const withContentlayer = createContentlayerPlugin({
  // Additional Contentlayer config options
})

export default withContentlayer({
  // Your Next.js config...
})

Was this article helpful to you?
Provide feedback

Last edited on March 31, 2023.
Edit this page