Contentlayer has full support for Next.js projects, including live reloading (if you follow the recommended approach below).

Installation & Configuration

Using Contentlayer in a Next.js project is easiest if you use the next-contentlayer plugin. Install the plugin:

npm install next-contentlayer

Then wrap your next configuration object in the withContentlayer utility.

// next.config.js
import { withContentlayer } from 'next-contentlayer'
export default withContentlayer({})

Working with Images

Image processing with Contentlayer is not currently supported, although we're planning on it. The current recommendation is to place images in the public directory, and then use a string field to store the path to that image.

Alternatively, you can store your images in an asset service like Cloudinary or Imgix. See here for more detail on our current recommendation for image processing.

Using next/image in Body Content

If you want to use next/image to render your images, create a component to wrap next/image and add the image via component markup in your markdown or MDX file.

For example, say we have an Image component in our project that wraps the next/image.

import Image as NextImage from 'next/image'

const Image = (props) => {
  return <NextImage /* ... */ />
}

You content should then call this component directly.

Other markdown content ...

<Image src="..." />

You can either use an .mdx file to have this content processed automatically, or you can use a tool like markdown-to-jsx with raw markdown.

Content live-reload (HMR)

Content live reload should work out-of-the-box with Next.js when using the next-contentlayer plugin and importing your content (e.g. import { allPosts } from 'contentlayer/generated') directly in your page app/components.

However, in some cases (due to a bug in Next.js) you might need to add the following hook to your app/page components:

import { useLiveReload } from 'next-contentlayer/hooks';
import { allPosts } from 'contentlayer/generated';

export function MyPage() {
  useLiveReload() // this only runs during development and has no impact on production

  return <div>Your app</div>
}

Using TypeScript

Using TypeScript with Next.js is optional, but we highly recommend it.

Next.js works great with TypeScript. Their docs show how to add TypeScript to new and existing projects. It also lists useful types provided by Next.js.

Using Preact

Preact can be used with a custom Webpack config. See this GitHub issue for details.


Was this article helpful to you?
Provide feedback

Last edited on March 31, 2023.
Edit this page