reactjstypescriptnext.jsmdxjs

Using MDX with NextJS 13 returning useContext error


I'm trying to use mdx files in Next.js 13. I've already done all the necessary configuration in next.config and created the file. Inside the app folder, I have > docs > components > accordion > page.mdx

The page file only renders a title like "# Title". When I navigate to this URL, I get the following error:

node_modules/@mdx-js/react/lib/index.js (34:26) @ React error - createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

How could I fix this?

my next.config.js

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [],
    rehypePlugins: [],
  },
})

/** @type {import('next').NextConfig} */
const nextConfig = {
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  experimental: {
    appDir: true,
  },
}

module.exports = withMDX(nextConfig)

Solution

  • At the root of your project, make sure to add the file mdx-components.tsx:

    import type { MDXComponents } from "mdx/types";
    
    // This file is required to use MDX in `app` directory.
    export function useMDXComponents(components: MDXComponents): MDXComponents {
      return {
        // Allows customizing built-in components, e.g. to add styling.
        // h1: ({ children }) => <h1 style={{ fontSize: "100px" }}>{children}</h1>,
        ...components,
      };
    }
    

    Also, my next.config.js looks like this (same as provided example bellow), but I've tried with yours and it's also working fine:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      experimental: {
        appDir: true,
      },
    };
    
    const withMDX = require("@next/mdx")();
    module.exports = withMDX(nextConfig);
    
    

    Also, you can take a look at this example: https://github.com/vercel/next.js/tree/canary/examples/app-dir-mdx