Blog>
Snippets

Setting Up MDX with Next.js 14

Setting up an MDX workflow by installing necessary packages and configuring your Next.js 14 project to support MDX.
npm install @next/mdx @mdx-js/loader
Install the required packages for MDX using npm. This command installs `@next/mdx`, which is the official Next.js plugin for MDX, and the `@mdx-js/loader` for webpack.
const withMDX = require('@next/mdx')({ extension: /\.(md|mdx)$/ });

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
});
Create a `next.config.js` in the root of your Next.js project, or modify the existing one. Here we're wrapping the Next.js configuration with the withMDX function, which enables MDX file processing, and we're specifying the file extensions for MDX files in addition to the default JavaScript and TypeScript file extensions.
import React from 'react';
import { MDXProvider } from '@mdx-js/react';

const components = {}; // Add custom components for MDX here

function MyApp({ Component, pageProps }) {
  return (
    <MDXProvider components={components}>
      <Component {...pageProps} />
    </MDXProvider>
  );
}

export default MyApp;
In your `_app.js` file (or `_app.tsx` if using TypeScript), wrap your components with `MDXProvider`. This allows you to customize the rendering of MDX content by providing a `components` prop, which can include custom components for markdown elements such as headings, links, etc.
<style jsx global>{`
  h1 {
    color: #0070f3;
  }
  p {
    color: #333;
  }
`}</style>
For styling your MDX content within Next.js, you can use either global CSS or CSS-in-JS libraries like styled-jsx. Here's an example using styled-jsx for global styles added inside a component, which styles h1 tags with a specific color.
import Content from './path/to/your/file.mdx';

const Page = () => <Content />;

export default Page;
In your Next.js pages, you can directly import MDX files as components and render them just like any other React component.