To create a documentation page showcasing the usage of Contentlayer with a Next.js app, specifically for managing content in MDX files located under a /content
folder, follow the steps below. This guide covers setting up Contentlayer, integrating it with a Next.js application, and demonstrating how to write, read, and modify content in MDX files.
Prerequisites
- Node.js and npm installed
Step 3: Configure Contentlayer
Create a new file named contentlayer.config.ts
in your project's root directory. This file will configure Contentlayer to use MDX files from your /content
folder.
import { defineDocumentType, makeSource } from '@contentlayer/source-files';
import remarkMdx from 'remark-mdx';
const Post = defineDocumentType(() => ({
name: 'Post',
filePathPattern: `**/*.mdx`,
contentType: 'mdx',
fields: {
title: { type: 'string', required: true },
date: { type: 'date', required: true },
author: { type: 'string', required: true },
},
}));
export default makeSource({
contentDirPath: 'content',
documentTypes: [Post],
mdx: { remarkPlugins: [remarkMdx] },
});
Step 4: Create MDX Content
Under your project root, create a folder named /content
and add MDX files. Each MDX file represents a piece of content, such as a blog post.
Example /content/my-first-post.mdx
:
---
title: "My First Post"
date: "2024-02-11"
author: "John Doe"
---
# Welcome to My First Post
This is a sample post to demonstrate how Contentlayer works with MDX in a Next.js application.
For a specific post, in pages/posts/[id].js
:
import { allPosts, Post } from 'contentlayer/generated';
import { useMDXComponent } from 'next-contentlayer/hooks';
import { useRouter } from 'next/router';
export default function PostPage({ post }) {
const MDXContent = useMDXComponent(post.body.code);
return (
<article>
<h1>{post.title}</h1>
<MDXContent />
</article>
);
}
export async function getStaticPaths() {
return {
paths: allPosts.map((post) => ({ params: { id: post._id } })),
fallback: false,
};
}