Web development

Adding an MDX blog to Next.js 16 on Turbopack

By 7 min read

In short

The problem

Adding an MDX blog to a Next.js 16 site on Turbopack fails twice: the build rejects remark and rehype plugins passed as imported functions, and a root-level mdx-components.js silently loses every Tailwind class in production.

What fixed it

Declare plugins as string names with JSON-serialisable options, keep mdx-components.js inside src/ so Tailwind's content glob reaches it, and read frontmatter with gray-matter on a channel separate from the compiled body.

On this page10 sections
  1. The setup in order
  2. The problem
  3. Why it happens
  4. The fix
  5. The second problem: Tailwind purges your MDX styles
  6. How the content layer is wired
  7. Troubleshooting
  8. What I would check first
  9. What this demonstrates
  10. Reading list
Adding an MDX blog to Next.js 16 on Turbopack
MDX, remark and rehype plugins, and Turbopack

I moved this site to Next.js 16 earlier this year, then went to add a blog to it. A good chunk of that work went into two problems that produce no useful error message. Both are specific to Turbopack being the default bundler in 16.x, and neither is obvious from the MDX guide.

Here is what broke and what actually fixed it, why each constraint exists, and what to check first if your own build misbehaves in the same way.

The short answer: on Turbopack, name your remark and rehype plugins as strings with plain-data options, and keep mdx-components.js inside src/ so Tailwind can see it.

The setup in order#

If you are starting from nothing, this is the order that avoids both problems:

  1. Install @next/mdx and the plugins you want as normal dependencies, so their package names can be resolved from the project.
  2. In next.config.mjs, wrap the config with createMDX and list plugins by string name, never by import.
  3. Add remark-frontmatter first in the remark list if your posts start with YAML.
  4. Create src/mdx-components.js exporting useMDXComponents() with no arguments.
  5. Compile the body through the route, and read frontmatter separately with gray-matter.
  6. Run a production build and look at the result, not only the dev server.

The rest of this post explains each step and where it goes wrong.

The problem#

The standard MDX setup looks like this in almost every tutorial written before 2025:

js
import remarkGfm from 'remark-gfm';
import rehypeSlug from 'rehype-slug';
 
const withMDX = createMDX({
  options: { remarkPlugins: [remarkGfm], rehypePlugins: [rehypeSlug] },
});

On Turbopack that build fails with a message about the MDX loader not having serializable options. Nothing in it points at the plugin array.

Why it happens#

Turbopack is written in Rust. It serialises its loader configuration before handing it across the JavaScript boundary, and an imported plugin is a function — there is no way to serialise one. Support for configuring plugins at all landed in Next 15.1, and it works by accepting the plugin's package name as a string and resolving it on the Rust side.

So the constraint is not "plugins don't work". It is that the plugin must be named rather than imported, and every option you pass alongside it has to survive JSON.stringify.

That second half is the one people miss. Strings, numbers, booleans, arrays and plain objects survive. Functions, regular expressions, dates and class instances do not, and a value that cannot be carried across the boundary either fails the build or arrives changed. Any option that your plugin documents as a callback is therefore off limits on this path, even when the plugin name itself is fine.

It also explains why the error is unhelpful. The failure happens when the configuration is being serialised, before any plugin has run, so the message is about the loader and not about the one option that caused it. The useful question is not "which plugin is broken" but "which value in this object is not plain data".

The fix#

js
const withMDX = createMDX({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: ['remark-frontmatter', 'remark-gfm'],
    rehypePlugins: [
      'rehype-slug',
      [
        'rehype-autolink-headings',
        {
          behavior: 'append',
          properties: { className: ['heading-anchor'] },
          // A hast node literal, not a function - this is the part that
          // usually trips people up, because the docs show a function here.
          content: {
            type: 'element',
            tagName: 'span',
            properties: {},
            children: [{ type: 'text', value: '#' }],
          },
        },
      ],
      ['rehype-pretty-code', { theme: 'github-dark-default', keepBackground: false }],
    ],
  },
});

Two things worth calling out.

remark-frontmatter is not optional if your posts use YAML frontmatter. Without it, MDX reads the opening --- as a thematic break and renders your title: and description: keys as visible body text at the top of the post.

The content option for rehype-autolink-headings is normally written as a function returning a hast node. That is exactly the kind of value Turbopack cannot serialise, so pass the node literal directly instead.

Order matters too. rehype-slug adds the id to each heading, and rehype-autolink-headings needs that id to build its links, so keep the slug plugin ahead of it in the list.

The second problem: Tailwind purges your MDX styles#

This one is worse, because the build passes.

Next.js accepts mdx-components.js at the repository root or inside src/. Most examples put it at the root. My tailwind.config.js, like most src/-based projects, scans:

js
content: ['./src/**/*.{js,ts,jsx,tsx,mdx}']

A root-level mdx-components.js sits outside that glob. Tailwind never sees the file, so every class in the component map is purged from the production stylesheet. Development uses a different build path and looks perfect. Production ships an unstyled blog.

The reason this stays hidden is that nothing is wrong with either tool. Tailwind only generates CSS for class names it finds in the files its content setting points at. It does not follow imports, so it has no way to know that a file outside the glob exists. Next.js, meanwhile, is happy to load mdx-components.js from either location. Both behave correctly, and the gap between them is yours to close.

The fix is one segment of path: put the file at src/mdx-components.js. If you would rather keep the file at the root, add its path to the content list instead, but moving it keeps the config simple.

Worth noting alongside it — the Next 16 signature changed, and useMDXComponents() now takes no arguments:

js
export function useMDXComponents() {
  return components;
}

How the content layer is wired#

One structural decision has paid off more than either fix: the body and the metadata are read through two independent channels.

The post body is compiled by @next/mdx through a dynamic import in the route. The frontmatter is read separately, straight off disk with gray-matter:

js
const readPost = (file) => {
  const slug = file.replace(/\.mdx?$/, '');
  const raw = fs.readFileSync(path.join(BLOG_DIR, file), 'utf8');
  const { data, content } = matter(raw);
  return { slug, ...data, ...readingStats(content) };
};

The reason is blast radius. sitemap.xml and llms.txt are built from that second channel, so they have no dependency on the MDX toolchain at all. An MDX compilation problem can break a single page without taking the machine-readable files down with it.

It removes a class of bug outright, too: the filename is the slug. There is no slug: frontmatter field, because a frontmatter slug that disagrees with the filename breaks the dynamic import in a way that is genuinely unpleasant to trace.

Troubleshooting#

SymptomLikely causeWhat to do
Build fails with an MDX loader serialisation messageA function, imported plugin or callback in the MDX optionsUse string plugin names, and replace function options with plain data
Frontmatter keys appear as text at the top of a postremark-frontmatter is missingAdd it to the remark plugins
Blog looks right in dev but unstyled in productionmdx-components.js is outside Tailwind's content globMove it to src/ or widen the glob
Headings have no anchor linksrehype-slug is missing or listed after the autolink pluginPut rehype-slug first
Code blocks lose highlighting or transformers are ignoredThe feature needs a function optionUse a local loader under turbopack.rules
A post fails to load by its URLThe slug and the filename disagreeDerive the slug from the filename and drop any slug: field

A few extra points that save time:

  • If a plugin cannot be found, check that it is installed as a dependency and that the string matches the package name exactly.
  • If you change next.config.mjs, restart the dev server. Config is read at start-up.
  • After fixing a styling problem, confirm in the production build, because dev can hide it.

What I would check first#

When an MDX blog misbehaves on Next.js 16 with Turbopack, I would go through this list in order:

  1. Is any plugin imported rather than named by string?
  2. Is every option plain data, with no functions, regular expressions or dates?
  3. Is remark-frontmatter in the remark list if posts use YAML?
  4. Does mdx-components.js live in src/, and does useMDXComponents() take no arguments?
  5. Does the Tailwind content glob cover that file?
  6. Does the production build, not just dev, look right?
  7. Does every filename match the slug the route expects?

Most problems of this kind are caught by the first two and the fifth.

What this demonstrates#

Both failures share a shape worth recognising. The first is loud and points nowhere useful. The second is completely silent and only appears in production. Neither is a bug in Next.js or in Tailwind — they are two tools doing exactly what they are designed to do, at a boundary where that behaviour is surprising.

When a build tool's error message doesn't name the thing that is actually wrong, the fastest way through is usually to stop reading the error and start asking what boundary the value had to cross.

Reading list#

A blog only helps if Google indexes it. I hit that problem next, and wrote it up in Crawled, currently not indexed: the cause was 173 words.

  • nextjs
  • seo

Common questions

Why does Turbopack reject remark and rehype plugins in next.config.mjs?

Turbopack is written in Rust and serialises its loader configuration before passing it across the JavaScript boundary. A plugin imported as a function cannot be serialised, so the build fails with a message about the MDX loader not having serializable options. Declare the plugin by its string name instead, and keep every option JSON-serialisable.

Where should mdx-components.js live in a Next.js project using Tailwind?

Inside src/, not the repository root, whenever tailwind.config.js scans ./src/**/*. Next.js accepts both locations, but a root-level file falls outside Tailwind's content glob, so every class named in the component map is purged from the production stylesheet. The blog then looks correct in development and unstyled in production.

Should blog frontmatter be read by the MDX pipeline or separately?

Separately. Compiling the body through MDX while reading frontmatter with gray-matter off disk keeps sitemap.xml and llms.txt independent of the MDX toolchain, so a compilation problem can break one page without taking the machine-readable files down with it.

How do I fix the MDX loader does not have serializable options error in Next.js?

Find every function, imported plugin or callback in the MDX options in next.config.mjs. Replace each imported plugin with its package name as a string, wrap options in an array next to that name, and turn any function-valued option into plain data such as a hast node literal. If a plugin truly needs a function, use a local loader instead.

Why do my YAML frontmatter keys show up as text at the top of an MDX post?

MDX does not understand YAML frontmatter on its own, so the opening three dashes are read as a thematic break and the keys render as body text. Add remark-frontmatter to the remark plugin list so the block is recognised and removed from the output.

Share this

Post it to LinkedIn

One click opens LinkedIn with a ready-written post: a hook, the short version of this guide and the link. The caption is also copied, so you can paste it if it does not appear.

Post it to Instagram

Instagram has no web share link, so this gives you both pieces: copy the caption, save the card, then post it.

Save the card

Got this problem too?

Websites, web apps and SaaS products in React and Next.js, with the backend, payments and integrations they need to actually run a business. The first call is free, and you get a written scope and price before any work starts.