hashicorp / next-mdx-remote

Load MDX content from anywhere
Mozilla Public License 2.0
2.68k stars 140 forks source link

How to pass custom data for use in MDX using next-mdx-remote/rsc in Nextjs 13.4 #390

Closed hanhanxue closed 1 year ago

hanhanxue commented 1 year ago

In the non RSC version of next-mdx-remote, we could pass custom data for use inside .mdx by passing the data to a scope prop like so:

<MDXRemote {...source} components={components} scope={data} />

But with next-mdx-remote/rsc the scope prop doesn't seem to be working:

const source = fs.readFileSync(mdxPath, 'utf8')
const {content, data} = matter(source)
const customData = { product: 'next' }

return (
<MDXRemote source={content} components={...components} scope={customData} />
)

When I try to access {product} inside mdx it says product is not defined

What's the correct way to send custom data through next-mdx-remote/rsc? Also is there a way to combine scope into the source like how you would do by passing scope to the serialize method in the past?

mryechkin commented 1 year ago

Here's how I'm doing it. Seems to work:

import { compileMDX } from 'next-mdx-remote/rsc';

const FOO = 'f00';
const BAR = 'b4r';

const source = `
**Foo**: <code>{FOO}</code>
**Bar**: <code>{BAR}</code>
`;

const { content, frontmatter } = await compileMDX({
    options: {
      parseFrontmatter: true,
      mdxOptions: {
        rehypePlugins,
        remarkPlugins,
      },
      scope: { FOO, BAR },
    },
    source
});

// return etc.