MDX in Next.js with App directory

MDX is a superset of markdown that lets you write JSX directly in your markdown files. It is a powerful way to add dynamic interactivity and embed React components within your content.

How do I set it up in my Next.js app?

Step 1 - Install required dependencies

npm install @next/mdx @mdx-js/loader @mdx-js/react

If you are using typescript also install

npm install -D @types/mdx

Step 2 - Create mdx-components.tsx

For Next.js app-router to work with MDX it requires a file named mdx-components.tsx in the root of the project

import type { MDXComponents } from 'mdx/types'
 
export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    ...components,
  }
}

Step 3 - Update next.config.js to use @next/mdx

const withMDX = require('@next/mdx')()
 
/** @type {import('next').NextConfig} */
const config = {
  // ... other config properties
  pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
}
 
module.exports = withMDX(config)

Step 4 -Create a page with .mdx extension

//project/app/mdx-pages/article-1/page.mdx
import { MyComponent } from 'my-components'
 
# Welcome to my MDX page!
 
This is some **bold** and _italics_ text.
 
This is a list in markdown:
 
- One
- Two
- Three
 
// You need to add this component in the mdx-components.tsx to be available here 
<MyComponent />

That's it, you can now use MDX inside of your app router in Next.js

For more detailed guide checkout official Next.js docs for MDX here

Next App RouterMdxNext
Avatar for Praveen Kumar

Written by Praveen Kumar

Full Stack @ Quizizz, Google Developer Students Lead, Moderator Codú Community

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.