next-mdx provides a set of helper functions for fetching and rendering local MDX files. It handles relational data, supports custom components, TypeScript ready and is fast.
next-mdx is great for building mdx-powered landing pages, multi-user blogs, category pages..etc.
TLDR
Table of Contents
Demo
https://next-mdx-example.vercel.app
Quick Start
Learn how next-mdx works by creating a sample project.
- Create a new blog using the simple-blog starter
npx create-next-app -e https://github.com/arshad/next-mdx-simple-blog
- Open
next-mdx.json
to see the sample configuration. - Open
pages/blog/[...slug].tsx
to see how MDX files are fetched and rendered. - See
types/index.d.ts
for TypeScript.
Installation
npm i --save next-mdx
Configuration
Create a next-mdx.json
file at the root of your project with the following:
{
"post": {
"contentPath": "content/posts",
"basePath": "/blog",
"sortBy": "date",
"sortOrder": "desc"
},
"category": {
"contentPath": "content/categories",
"basePath": "/blog/categories"
}
}
post
andcategory
keys are unique IDs used as references for your MDX types.contentPath
(required) is where your MDX files are located.basePath
(required) is the path used for generating URLs.sortBy
(optional, defaults totitle
) is the name of the frontMatter field used for sorting.sortOrder
(optional, defaults toasc
) is the sorting order.
Reference
next-mdx
exposes four main helper functions:
getMdxPaths
getMdxPaths(sourceName: string)
returns an array of path params which can be passed directly to paths in
getStaticPaths`.
sourceName
is the unique ID defined innext-mdx.json
Example
// pages/blog/[...slug].js
import { getMdxPaths } from "next-mdx/server"
export async function getStaticPaths() {
return {
paths: await getMdxPaths("post"),
fallback: false,
}
}
getMdxNode
getMdxNode(sourceName, context, params)
returns an MDXNode
.
sourceName
is the unique ID defined innext-mdx.json
context
is the context passed togetStaticProps
.params
:
{
components?: MdxRemote.Components
scope?: Record<string, unknown>
provider?: MdxRemote.Provider
mdxOptions?: {
remarkPlugins?: Pluggable[]
rehypePlugins?: Pluggable[]
hastPlugins?: Pluggable[]
compilers?: Compiler[]
filepath?: string
}
}
Example
// pages/blog/[...slug].js
import { getMdxNode } from "next-mdx/server"
export async function getStaticProps(context) {
const post = await getMdxNode("post", context)
if (!post) {
return {
notFound: true,
}
}
return {
props: {
post,
},
}
}
getAllMdxNodes
getAllMdxNodes(sourceName, params)
returns all MdxNode
of the given type/source.
sourceName
is the unique ID defined innext-mdx.json
params
:
{
components?: { name: React.Component },
scope?: {},
provider?: { component: React.Component, props: Record<string, unknown> },
mdxOptions: {
remarkPlugins: [],
rehypePlugins: [],
hastPlugins: [],
compilers: [],
}
}
Example
import { getAllMdxNodes } from "next-mdx/server"
export async function getStaticProps() {
const posts = await getAllMdxNodes("post")
return {
props: {
posts: posts.filter((post) => post.frontMatter.featured),
},
}
}
useHydrate
useHydrate(node, params)
is used on the client side for hydrating static content.
node
is theMdxNode
objectparams
:
{
components?: { name: React.Component },
provider?: { component: React.Component, props: Record<string, unknown> }
}
Example
import { useHydrate } from "next-mdx/client"
export default function PostPage({ post }) {
const content = useHydrate(post)
return (
<div>
<h1>{post.frontMatter.title}</h1>
{content}
</div>
)
}
MDX Components
To use components inside MDX files, you need to pass the components to both getMdxNode/getMdxNodes
and useHydrate
.
Example
import { getMdxNode } from "next-mdx/server"
import { useHydrate } from "next-mdx/client"
export function Alert({ text }) {
return <p>{text}</p>
}
export default function PostPage({ post }) {
const content = useHydrate(post, {
components: {
Alert,
},
})
return (
<div>
<h1>{post.frontMatter.title}</h1>
{content}
</div>
)
}
export async function getStaticProps(context) {
const post = await getMdxNode("post", context, {
components: {
Alert,
},
})
return {
props: {
post,
},
}
}
Relational Data
When retrieving nodes with getMdxNode
or getAllMdxNodes
, next-mdx
will automatically infer relational data from frontMatter keys.
Convention
- The frontMatter field name must be the same as the key defined in
next-mdx.json
- The frontMatter field must be an array of values.
Example
Given the following MDX files.
.
└── content
├── categories
│ └── category-a.mdx
│ └── category-b.mdx
└── posts:
└── example-post.mdx
In example-post
you can reference related categories using the following:
---
title: Example Post
category:
- category-a
---
You can then access the categories as follows:
const post = getMdxNode("post", context)
// post.relationships.category
License
Licensed under the MIT license.