Installations
npm install next-mdx-remote
Developer
hashicorp
Developer Guide
Module System
ESM
Min. Node Version
>=14
Typescript Support
Yes
Node Version
20.13.1
NPM Version
10.5.2
Statistics
2,736 Stars
184 Commits
141 Forks
29 Watching
13 Branches
88 Contributors
Updated on 28 Nov 2024
Languages
TypeScript (79.87%)
JavaScript (18.03%)
MDX (2.1%)
Total Downloads
Cumulative downloads
Total Downloads
17,080,594
Last day
0.6%
40,093
Compared to previous day
Last week
4.5%
222,438
Compared to previous week
Last month
2.4%
943,088
Compared to previous month
Last year
98.6%
9,357,188
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
1
Dev Dependencies
26
Installation
1npm install next-mdx-remote
If using with Turbopack, you'll need to add the following to your next.config.js
until this issue is resolved:
1const nextConfig = { 2+ transpilePackages: ['next-mdx-remote'], 3}
Examples
1import { serialize } from 'next-mdx-remote/serialize' 2import { MDXRemote } from 'next-mdx-remote' 3 4import Test from '../components/test' 5 6const components = { Test } 7 8export default function TestPage({ source }) { 9 return ( 10 <div className="wrapper"> 11 <MDXRemote {...source} components={components} /> 12 </div> 13 ) 14} 15 16export async function getStaticProps() { 17 // MDX text - can be from a local file, database, anywhere 18 const source = 'Some **mdx** text, with a component <Test />' 19 const mdxSource = await serialize(source) 20 return { props: { source: mdxSource } } 21}
While it may seem strange to see these two in the same file, this is one of the cool things about Next.js -- getStaticProps
and TestPage
, while appearing in the same file, run in two different places. Ultimately your browser bundle will not include getStaticProps
at all, or any of the functions it uses only on the server, so serialize
will be removed from the browser bundle entirely.
IMPORTANT: Be very careful about putting any
next-mdx-remote
code into a separate "utilities" file. Doing so will likely cause issues with Next.js' code splitting abilities - it must be able to cleanly determine what is used only on the server side and what should be left in the client bundle. If you putnext-mdx-remote
code into an external utilities file and something is broken, remove it and start from the simple example above before filing an issue.
Additional Examples
Parsing Frontmatter
Markdown in general is often paired with frontmatter, and normally this means adding some extra custom processing to the way markdown is handled. To address this, next-mdx-remote
comes with optional parsing of frontmatter, which can be enabled by passing parseFrontmatter: true
to serialize
.
Here's what that looks like:
1import { serialize } from 'next-mdx-remote/serialize' 2import { MDXRemote } from 'next-mdx-remote' 3 4import Test from '../components/test' 5 6const components = { Test } 7 8export default function TestPage({ mdxSource }) { 9 return ( 10 <div className="wrapper"> 11 <h1>{mdxSource.frontmatter.title}</h1> 12 <MDXRemote {...mdxSource} components={components} /> 13 </div> 14 ) 15} 16 17export async function getStaticProps() { 18 // MDX text - can be from a local file, database, anywhere 19 const source = `--- 20title: Test 21--- 22 23Some **mdx** text, with a component <Test name={frontmatter.title}/> 24 ` 25 26 const mdxSource = await serialize(source, { parseFrontmatter: true }) 27 return { props: { mdxSource } } 28}
vfile-matter
is used to parse the frontmatter.
Passing custom data to a component with `scope`
<MDXRemote />
accepts a scope
prop, which makes all of the values available for use in your MDX.
Each key/value pair in the scope
argument will be exposed as a javascript variable. So, for example, you could imagine if you had a scope like { foo: 'bar' }
, it would be interpreted as const foo = 'bar'
.
This specifically means that you need to make sure that key names in your scope
argument are valid javascript variable names. For example, passing in { 'my-variable-name': 'bar' }
would generate an error, because the key name is not a valid javascript variable name.
It's also important to note that scope
variables must be consumed as arguments to a component, they cannot be rendered in the middle of text. This is shown in the example below.
1import { serialize } from 'next-mdx-remote/serialize' 2import { MDXRemote } from 'next-mdx-remote' 3 4import Test from '../components/test' 5 6const components = { Test } 7const data = { product: 'next' } 8 9export default function TestPage({ source }) { 10 return ( 11 <div className="wrapper"> 12 <MDXRemote {...source} components={components} scope={data} /> 13 </div> 14 ) 15} 16 17export async function getStaticProps() { 18 // MDX text - can be from a local file, database, anywhere 19 const source = 20 'Some **mdx** text, with a component using a scope variable <Test product={product} />' 21 const mdxSource = await serialize(source) 22 return { props: { source: mdxSource } } 23}
Passing `scope` into the `serialize` function instead
You can also pass custom data into serialize
, which will then pass the value through and make it available from its result. By spreading the result from source
into <MDXRemote />
, the data will be made available.
Note that any scope values passed into serialize
need to be serializable, meaning passing functions or components is not possible. Additionally, any key named in the scope
argument must be valid javascript variable names. If you need to pass custom scope that is not serializable, you can pass scope
directly to <MDXRemote />
where it's rendered. There is an example of how to do this above this section.
1import { serialize } from 'next-mdx-remote/serialize' 2import { MDXRemote } from 'next-mdx-remote' 3 4import Test from '../components/test' 5 6const components = { Test } 7const data = { product: 'next' } 8 9export default function TestPage({ source }) { 10 return ( 11 <div className="wrapper"> 12 <MDXRemote {...source} components={components} /> 13 </div> 14 ) 15} 16 17export async function getStaticProps() { 18 // MDX text - can be from a local file, database, anywhere 19 const source = 20 'Some **mdx** text, with a component <Test product={product} />' 21 const mdxSource = await serialize(source, { scope: data }) 22 return { props: { source: mdxSource } } 23}
Custom components from MDXProvider
If you want to make components available to any <MDXRemote />
being rendered in your application, you can use <MDXProvider />
from @mdx-js/react
.
1// pages/_app.jsx 2import { MDXProvider } from '@mdx-js/react' 3 4import Test from '../components/test' 5 6const components = { Test } 7 8export default function MyApp({ Component, pageProps }) { 9 return ( 10 <MDXProvider components={components}> 11 <Component {...pageProps} /> 12 </MDXProvider> 13 ) 14}
1// pages/test.jsx 2import { serialize } from 'next-mdx-remote/serialize' 3import { MDXRemote } from 'next-mdx-remote' 4 5export default function TestPage({ source }) { 6 return ( 7 <div className="wrapper"> 8 <MDXRemote {...source} /> 9 </div> 10 ) 11} 12 13export async function getStaticProps() { 14 // MDX text - can be from a local file, database, anywhere 15 const source = 'Some **mdx** text, with a component <Test />' 16 const mdxSource = await serialize(source) 17 return { props: { source: mdxSource } } 18}
Component names with dot (e.g. motion.div
)
Component names that contain a dot (.
), such as those from framer-motion
, can be rendered the same way as other custom components, just pass motion
in your components object.
1import { motion } from 'framer-motion' 2 3import { MDXProvider } from '@mdx-js/react' 4import { serialize } from 'next-mdx-remote/serialize' 5import { MDXRemote } from 'next-mdx-remote' 6 7export default function TestPage({ source }) { 8 return ( 9 <div className="wrapper"> 10 <MDXRemote {...source} components={{ motion }} /> 11 </div> 12 ) 13} 14 15export async function getStaticProps() { 16 // MDX text - can be from a local file, database, anywhere 17 const source = `Some **mdx** text, with a component: 18 19<motion.div animate={{ x: 100 }} />` 20 const mdxSource = await serialize(source) 21 return { props: { source: mdxSource } } 22}
Lazy hydration
Lazy hydration defers hydration of the components on the client. This is an optimization technique to improve the initial load of your application, but may introduce unexpected delays in interactivity for any dynamic content within your MDX content.
Note: this will add an additional wrapping div
around your rendered MDX, which is necessary to avoid hydration mismatches during render.
1import { serialize } from 'next-mdx-remote/serialize' 2import { MDXRemote } from 'next-mdx-remote' 3 4import Test from '../components/test' 5 6const components = { Test } 7 8export default function TestPage({ source }) { 9 return ( 10 <div className="wrapper"> 11 <MDXRemote {...source} components={components} lazy /> 12 </div> 13 ) 14} 15 16export async function getStaticProps() { 17 // MDX text - can be from a local file, database, anywhere 18 const source = 'Some **mdx** text, with a component <Test />' 19 const mdxSource = await serialize(source) 20 return { props: { source: mdxSource } } 21}
APIs
This library exposes a function and a component, serialize
and <MDXRemote />
. These two are purposefully isolated into their own files -- serialize
is intended to be run server-side, so within getStaticProps
, which runs on the server/at build time. <MDXRemote />
on the other hand is intended to be run on the client side, in the browser.
-
serialize(source: string, { mdxOptions?: object, scope?: object, parseFrontmatter?: boolean })
serialize
consumes a string of MDX. It can also optionally be passed options which are passed directly to MDX, and a scope object that can be included in the MDX scope. The function returns an object that is intended to be passed into<MDXRemote />
directly.1serialize( 2 // Raw MDX contents as a string 3 '# hello, world', 4 // Optional parameters 5 { 6 // made available to the arguments of any custom MDX component 7 scope: {}, 8 // MDX's available options, see the MDX docs for more info. 9 // https://mdxjs.com/packages/mdx/#compilefile-options 10 mdxOptions: { 11 remarkPlugins: [], 12 rehypePlugins: [], 13 format: 'mdx', 14 }, 15 // Indicates whether or not to parse the frontmatter from the MDX source 16 parseFrontmatter: false, 17 } 18)
Visit https://mdxjs.com/packages/mdx/#compilefile-options for available
mdxOptions
. -
<MDXRemote compiledSource={string} components?={object} scope?={object} lazy?={boolean} />
<MDXRemote />
consumes the output ofserialize
as well as an optional components argument. Its result can be rendered directly into your component. To defer hydration of the content and immediately serve the static markup, pass thelazy
prop.1<MDXRemote {...source} components={components} />
Replacing default components
Rendering will use MDXProvider
under the hood. This means you can replace HTML tags by custom components. Those components are listed in MDXJS Table of components.
An example use case is rendering the content with your preferred styling library.
1import { Typography } from "@material-ui/core"; 2 3const components = { Test, h2: (props) => <Typography variant="h2" {...props} /> } 4...
If you prefer, you can also wrap your entire application in an <MDXProvider />
instead of passing your components directly to <MDXRemote />
. See the example above.
Note: th/td
won't work because of the "/" in the component name.
Background & Theory
There isn't really a good default way to load MDX files in a Next.js app. Previously, we wrote next-mdx-enhanced
in order to be able to render your MDX files into layouts and import their front matter to create index pages.
This workflow from next-mdx-enhanced
was fine, but introduced a few limitations that we have removed with next-mdx-remote
:
- The file content must be local. You cannot store MDX files in another repo, a database, etc. For a large enough operation, there will end up being a split between those authoring content and those working on presentation of the content. Overlapping these two concerns in the same repo makes a more difficult workflow for everyone.
- You are bound to filesystem-based routing. Your pages are generated with urls according to their locations. Or maybe you remap them using
exportPathMap
, which creates confusion for authors. Regardless, moving pages around in any way breaks things -- either the page's url or yourexportPathMap
configuration. - You will end up running into performance issues. Webpack is a JavaScript bundler, forcing it to load hundreds/thousands of pages of text content will blow out your memory requirements. Webpack stores each page as a distinct object with a large amount of metadata. One of our implementations with a couple hundred pages hit more than 8GB of memory required to compile the site. Builds took more than 25 minutes.
- You will be limited in the ways you are able to structure relational data. Organizing content into dynamic, related categories is difficult when your entire data structure is front matter parsed into javascript objects and held in memory.
So, next-mdx-remote
changes the entire pattern so that you load your MDX content not through an import, but rather through getStaticProps
or getServerProps
-- you know, the same way you would load any other data. The library provides the tools to serialize and hydrate the MDX content in a manner that is performant. This removes all of the limitations listed above, and does so at a significantly lower cost -- next-mdx-enhanced
is a very heavy library with a lot of custom logic and some annoying limitations. Our informal testing has shown build times reduced by 50% or more.
Since this project was initially created, Kent C. Dodds has made a similar project, mdx-bundler
. This library supports imports and exports within a MDX file (as long as you manually read each imported file and pass its contents) and automatically processes frontmatter. If you have a lot of files that all import and use different components, you may benefit from using mdx-bundler
, as next-mdx-remote
currently only allows components to be imported and made available across all pages. It's important to note that this functionality comes with a cost though - mdx-bundler
's output is at least 400% larger than the output from next-mdx-remote
for basic markdown content.
How Can I Build A Blog With This?
Data has shown that 99% of use cases for all developer tooling are building unnecessarily complex personal blogs. Just kidding. But seriously, if you are trying to build a blog for personal or small business use, consider just using normal HTML and CSS. You definitely do not need to be using a heavy full-stack JavaScript framework to make a simple blog. You'll thank yourself later when you return to make an update in a couple years and there haven't been 10 breaking releases to all of your dependencies.
If you really insist though, check out our official Next.js example implementation. 💖
Caveats
Environment Targets
The code generated by next-mdx-remote
, which is used to actually render the MDX targets browsers with module support. If you need to support older browsers, consider transpiling the compiledSource
output from serialize
.
import
/ export
import
and export
statements cannot be used inside an MDX file. If you need to use components in your MDX files, they should be provided as a prop to <MDXRemote />
.
Hopefully this makes sense, since in order to work, imports must be relative to a file path, and this library allows content to be loaded from anywhere, rather than only loading local content from a set file path. As for exports, the MDX content is treated as data, not a module, so there is no way for us to access any value which may be exported from the MDX passed to next-mdx-remote
.
Security
This library evaluates a string of JavaScript on the client side, which is how it MDXRemotes the MDX content. Evaluating a string into javascript can be a dangerous practice if not done carefully, as it can enable XSS attacks. It's important to make sure that you are only passing the mdxSource
input generated by the serialize
function to <MDXRemote />
, as instructed in the documentation. Do not pass user input into <MDXRemote />
.
If you have a CSP on your website that disallows code evaluation via eval
or new Function()
, you will need to loosen that restriction in order to utilize next-mdx-remote
, which can be done using unsafe-eval
.
TypeScript
This project does include native types for TypeScript use. Both serialize
and <MDXRemote />
have types normally as you'd expect, and the library also exports a type which you can use to type the result of getStaticProps
.
MDXRemoteSerializeResult<TScope = Record<string, unknown>>
: Represents the return value ofserialize
. TheTScope
generic type can be passed to represent the type of the scoped data you pass in.
Below is an example of a simple implementation in TypeScript. You may not need to implement the types exactly in this way for every configuration of TypeScript - this example is just a demonstration of where the types could be applied if needed.
1import type { GetStaticProps } from 'next' 2import { serialize } from 'next-mdx-remote/serialize' 3import { MDXRemote, type MDXRemoteSerializeResult } from 'next-mdx-remote' 4import ExampleComponent from './example' 5 6const components = { ExampleComponent } 7 8interface Props { 9 mdxSource: MDXRemoteSerializeResult 10} 11 12export default function ExamplePage({ mdxSource }: Props) { 13 return ( 14 <div> 15 <MDXRemote {...mdxSource} components={components} /> 16 </div> 17 ) 18} 19 20export const getStaticProps: GetStaticProps<{ 21 mdxSource: MDXRemoteSerializeResult 22}> = async () => { 23 const mdxSource = await serialize('some *mdx* content: <ExampleComponent />') 24 return { props: { mdxSource } } 25}
React Server Components (RSC) & Next.js app
Directory Support
Usage of next-mdx-remote
within server components, and specifically within Next.js's app
directory, is supported by importing from next-mdx-remote/rsc
. Previously, the serialization and render steps were separate, but going forward RSC makes this separation unnecessary.
Some noteworthy differences:
<MDXRemote />
now accepts asource
prop, instead of accepting the serialized output fromnext-mdx-remote/serialize
- Custom components can no longer be provided by using the
MDXProvider
context from@mdx-js/react
, as RSC does not support React Context - To access frontmatter outside of your MDX when passing
parseFrontmatter: true
, use thecompileMdx
method exposed fromnext-mdx-remote/rsc
- The
lazy
prop is no longer supported, as the rendering happens on the server <MDXRemote />
must be rendered on the server, as it is now an async component. Client components can be rendered as part of the MDX markup
For more information on RSC, check out the Next.js documentation.
Examples
Assuming usage in a Next.js 13+ application using the app
directory.
Basic
1import { MDXRemote } from 'next-mdx-remote/rsc' 2 3// app/page.js 4export default function Home() { 5 return ( 6 <MDXRemote 7 source={`# Hello World 8 9 This is from Server Components! 10 `} 11 /> 12 ) 13}
Loading state
1import { MDXRemote } from 'next-mdx-remote/rsc' 2 3// app/page.js 4export default function Home() { 5 return ( 6 // Ideally this loading spinner would ensure there is no layout shift, 7 // this is an example for how to provide such a loading spinner. 8 // In Next.js you can also use `loading.js` for this. 9 <Suspense fallback={<>Loading...</>}> 10 <MDXRemote 11 source={`# Hello World 12 13 This is from Server Components! 14 `} 15 /> 16 </Suspense> 17 ) 18}
Custom Components
1// components/mdx-remote.js 2import { MDXRemote } from 'next-mdx-remote/rsc' 3 4const components = { 5 h1: (props) => ( 6 <h1 {...props} className="large-text"> 7 {props.children} 8 </h1> 9 ), 10} 11 12export function CustomMDX(props) { 13 return ( 14 <MDXRemote 15 {...props} 16 components={{ ...components, ...(props.components || {}) }} 17 /> 18 ) 19}
1// app/page.js 2import { CustomMDX } from '../components/mdx-remote' 3 4export default function Home() { 5 return ( 6 <CustomMDX 7 // h1 now renders with `large-text` className 8 source={`# Hello World 9 This is from Server Components! 10 `} 11 /> 12 ) 13}
Access Frontmatter outside of MDX
1// app/page.js 2import { compileMDX } from 'next-mdx-remote/rsc' 3 4export default async function Home() { 5 // Optionally provide a type for your frontmatter object 6 const { content, frontmatter } = await compileMDX<{ title: string }>({ 7 source: `--- 8title: RSC Frontmatter Example 9--- 10# Hello World 11This is from Server Components! 12`, 13 options: { parseFrontmatter: true }, 14 }) 15 return ( 16 <> 17 <h1>{frontmatter.title}</h1> 18 {content} 19 </> 20 ) 21}
Alternatives
next-mdx-remote
is opinionated in what features it supports. If you need additional features not provided by next-mdx-remote
, here are a few alternatives to consider:
You Might Not Need next-mdx-remote
If you're using React Server Components and just trying to use basic MDX with custom components, you don't need anything other than the core MDX library.
1import { compile, run } from '@mdx-js/mdx' 2import * as runtime from 'react/jsx-runtime' 3import ClientComponent from './components/client' 4 5// MDX can be retrieved from anywhere, such as a file or a database. 6const mdxSource = `# Hello, world! 7<ClientComponent /> 8` 9 10export default async function Page() { 11 // Compile the MDX source code to a function body 12 const code = String( 13 await compile(mdxSource, { outputFormat: 'function-body' }) 14 ) 15 // You can then either run the code on the server, generating a server 16 // component, or you can pass the string to a client component for 17 // final rendering. 18 19 // Run the compiled code with the runtime and get the default export 20 const { default: MDXContent } = await run(code, { 21 ...runtime, 22 baseUrl: import.meta.url, 23 }) 24 25 // Render the MDX content, supplying the ClientComponent as a component 26 return <MDXContent components={{ ClientComponent }} /> 27}
You can also simplify this approach with evaluate
, which compiles and runs code in a single call if you don't plan on passing the compiled string to a database or client component.
1import { evaluate } from '@mdx-js/mdx' 2import * as runtime from 'react/jsx-runtime' 3import ClientComponent from './components/client' 4 5// MDX can be retrieved from anywhere, such as a file or a database. 6const mdxSource = ` 7export const title = "MDX Export Demo"; 8 9# Hello, world! 10<ClientComponent /> 11 12export function MDXDefinedComponent() { 13 return <p>MDX-defined component</p>; 14} 15` 16 17export default async function Page() { 18 // Run the compiled code 19 const { 20 default: MDXContent, 21 MDXDefinedComponent, 22 ...rest 23 } = await evaluate(mdxSource, runtime) 24 25 console.log(rest) // logs { title: 'MDX Export Demo' } 26 27 // Render the MDX content, supplying the ClientComponent as a component, and 28 // the exported MDXDefinedComponent. 29 return ( 30 <> 31 <MDXContent components={{ ClientComponent }} /> 32 <MDXDefinedComponent /> 33 </> 34 ) 35}
License
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
all dependencies are pinned
Details
- Info: 4 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 2 out of 2 third-party GitHubAction dependencies pinned
- Info: 2 out of 2 npmCommand dependencies pinned
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: Mozilla Public License 2.0: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/hashicorp/.github/SECURITY.md:1
- Info: Found linked content: github.com/hashicorp/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/hashicorp/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/hashicorp/.github/SECURITY.md:1
Reason
Found 8/18 approved changesets -- score normalized to 4
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/canary-release.yml:1
- Warn: no topLevel permission defined: .github/workflows/release.yml:1
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 25 are checked with a SAST tool
Reason
23 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9vvw-cc9w-f27h
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
- Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-c59h-r6p8-q9wc
- Warn: Project is vulnerable to: GHSA-g77x-44xx-532m
- Warn: Project is vulnerable to: GHSA-w7rc-rwvf-8q5r
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-hj48-42vr-x3v9
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-7fh5-64p2-3v2j
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-w5p7-h5w8-2hfq
- Warn: Project is vulnerable to: GHSA-8jhw-289h-jh2g
- Warn: Project is vulnerable to: GHSA-64vr-g452-qvp3
- Warn: Project is vulnerable to: GHSA-9cwx-2883-4wfx
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
4.1
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More