Skip to content

Commit dfbda44

Browse files
Griko Nibrasjescalan
Griko Nibras
authored andcommitted
Update readme
1 parent b044dad commit dfbda44

File tree

2 files changed

+104
-63
lines changed

2 files changed

+104
-63
lines changed

README.md

+104-63
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,57 @@
1-
# Next MDX Remote
1+
<!-- markdownlint-disable-file MD033 MD041 -->
2+
3+
<!--
4+
5+
# next-mdx-remote
26
37
A set of light utilities allowing mdx to be loaded within `getStaticProps` or `getServerSideProps` and hydrated correctly on the client.
48
5-
### Background & Theory
9+
-->
610

7-
If you are using mdx within a nextjs app, you are probably using the webpack loader. This means that you have your mdx files locally and are probably using [next-mdx-enhanced](https://github.com/hashicorp/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 is fine, but introduces a few limitations that we aim to remove with `next-mdx-remote`:
11+
[![next-mdx-remote](./header.png)](.)
812

9-
- 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.
10-
- 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 your `exportPathMap` configuration.
11-
- 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.
12-
- 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.
13+
---
1314

14-
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](https://github.com/hashicorp/next-mdx-enhanced/issues/17). Early testing has shown build times reduced by 50% or more.
15+
- [Background & Theory](#background--theory)
16+
- [Installation](#installation)
17+
- [Example Usage](#example-usage)
18+
- [APIs](#apis)
19+
- [Frontmatter & Custom Processing](#frontmatter--custom-processing)
20+
- [Caveats](#caveats)
21+
- [Security](#security)
22+
- [License](#license)
1523

16-
### Installation
24+
---
1725

18-
```
19-
npm i next-mdx-remote
20-
```
26+
## Background & Theory
2127

22-
### Usage
28+
If you are using MDX within a Next.js app, you are probably using the Webpack loader. This means that you have your MDX files locally and are probably using [`next-mdx-enhanced`](https://github.com/hashicorp/next-mdx-enhanced) in order to be able to render your MDX files into layouts and import their front matter to create index pages.
2329

24-
This library exposes two functions, `renderToString` and `hydrate`, much like `react-dom`. These two are purposefully isolated into their own files -- `renderToString` is intended to be run **server-side**, so within `getStaticProps`, which runs on the server/at build time. `hydrate` on the other hand is intended to be run on the client side, in the browser.
30+
This workflow is fine, but introduces a few limitations that we aim to remove with `next-mdx-remote`:
2531

26-
First let's break down each function's signature in some pseudo-typescript-y format, then we'll look at an example:
27-
28-
```typescript
29-
renderToString(
30-
// raw mdx contents as a string
31-
source: String,
32-
options?: {
33-
// the `name` is how you will invoke the component in your mdx
34-
components: { name: React.ComponentType },
35-
// mdx's available options at time of writing
36-
// pulled directly from https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js
37-
mdxOptions: {
38-
remarkPlugins: []any,
39-
rehypePlugins: []any,
40-
hastPlugins: []any,
41-
compilers: []any,
42-
filepath: String
43-
},
44-
// variable names and values which can be consumed by components
45-
scope: { [key:string]: any }
46-
}
47-
)
48-
```
32+
- **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.
33+
- **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 your `exportPathMap` configuration.
34+
- **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.
35+
- **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.
36+
37+
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](https://github.com/hashicorp/next-mdx-enhanced/issues/17). Early testing has shown build times reduced by 50% or more.
38+
39+
## Installation
4940

50-
```typescript
51-
hydrate(
52-
// the direct return value of `renderToString`
53-
source: CompiledMdxSourceType,
54-
// should be the exact same components that were passed to renderToString
55-
options?: {
56-
components: { name: React.ComponentType }
57-
}
58-
)
41+
```sh
42+
# using npm
43+
npm i next-mdx-remote
44+
45+
# using yarn
46+
yarn add next-mdx-remote
5947
```
6048

61-
Ok with that out of the way, let's look at an example for the normal use case:
49+
## Example Usage
6250

6351
```jsx
6452
import renderToString from 'next-mdx-remote/render-to-string'
6553
import hydrate from 'next-mdx-remote/hydrate'
54+
6655
import Test from '../components/test'
6756

6857
const components = { Test }
@@ -73,30 +62,76 @@ export default function TestPage({ source }) {
7362
}
7463

7564
export async function getStaticProps() {
76-
// mdx text - can be from a local file, database, anywhere
65+
// MDX text - can be from a local file, database, anywhere
7766
const source = 'Some **mdx** text, with a component <Test />'
7867
const mdxSource = await renderToString(source, { components })
7968
return { props: { source: mdxSource } }
8069
}
8170
```
8271

83-
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 only it uses, so `renderToString` will be removed from the browser bundle entirely.
72+
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 only it uses, so `renderToString` will be removed from the browser bundle entirely.
73+
74+
## APIs
8475

85-
Let's break down each function:
76+
This library exposes two functions, `renderToString` and `hydrate`, much like `react-dom`. These two are purposefully isolated into their own files -- `renderToString` is intended to be run **server-side**, so within `getStaticProps`, which runs on the server/at build time. `hydrate` on the other hand is intended to be run on the client side, in the browser.
77+
78+
- **`renderToString(source: string, components: object, options?: object, scope?: object)`**
79+
80+
**`renderToString`** consumes a string of MDX along with any components it utilizes in the format `{ ComponentName: ActualComponent }`. It also can optionally be passed options which are [passed directly to MDX](https://mdxjs.com/advanced/plugins), and a scope object that can be included in the mdx scope. The function returns an object that is intended to be passed into `hydrate` directly.
81+
82+
```ts
83+
renderToString({
84+
// Raw MDX contents as a string
85+
source: '# hello, world',
86+
// Optional parameters
87+
options: {
88+
// The `name` is how you will invoke the component in your MDX
89+
components: { name: React.ComponentType },
90+
// MDX's available options at time of writing pulled directly from
91+
// https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js
92+
mdxOptions: {
93+
remarkPlugins: [],
94+
rehypePlugins: [],
95+
hastPlugins: [],
96+
compilers: [],
97+
filepath: '/some/file/path',
98+
},
99+
},
100+
scope: {},
101+
})
102+
```
103+
104+
Visit <https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js> for available `mdxOptions`.
105+
106+
- **`hydrate(source: object, components: object)`**
107+
108+
**`hydrate`** consumes the output of `renderToString` as well as the same components argument as `renderToString`. Its result can be rendered directly into your component. This function will initially render static content, and hydrate it when the browser isn't busy with higher priority tasks.
109+
110+
```ts
111+
hydrate(
112+
// The direct return value of `renderToString`
113+
source,
114+
// Should be the exact same components that were passed to `renderToString`
115+
{
116+
components: { name: React.ComponentType },
117+
}
118+
)
119+
```
86120

87-
- `renderToString(source: string, components: object, options?: object, scope?: object)` - This function consumes a string of mdx along with any components it utilizes in the format `{ ComponentName: ActualComponent }`. It also can optionally be passed options which are [passed directly to mdx](https://mdxjs.com/advanced/plugins), and a scope object that can be included in the mdx scope. The function returns an object that is intended to be passed into `hydrate` directly.
88-
- `hydrate(source: object, components: object)` - This function consumes the output of `renderToString` as well as the same components argument as `renderToString`. Its result can be rendered directly into your component. This function will initially render static content, and hydrate it when the browser isn't busy with higher priority tasks.
121+
## Frontmatter & Custom Processing
89122

90-
### Frontmatter & Custom Processing
123+
Markdown in general is often paired with frontmatter, and normally this means adding some extra custom processing to the way markdown is handled. Luckily, this can be done entirely independently of `next-mdx-remote`, along with any extra custom processing necessary.
91124

92-
Markdown in general is often paired with frontmatter, and normally this means adding some extra custom processing to the way markdown is handled. Luckily, this can be done entirely independently of `next-mdx-remote`, along with any extra custom processing necessary. Let's walk through an example of how we could process frontmatter out of our mdx source.
125+
Let's walk through an example of how we could process frontmatter out of our MDX source:
93126

94127
```jsx
95128
import renderToString from 'next-mdx-remote/render-to-string'
96129
import hydrate from 'next-mdx-remote/hydrate'
97-
import Test from '../components/test'
130+
98131
import matter from 'gray-matter'
99132

133+
import Test from '../components/test'
134+
100135
const components = { Test }
101136

102137
export default function TestPage({ source, frontMatter }) {
@@ -110,13 +145,15 @@ export default function TestPage({ source, frontMatter }) {
110145
}
111146

112147
export async function getStaticProps() {
113-
// mdx text - can be from a local file, database, anywhere
114-
const source = `---
148+
// MDX text - can be from a local file, database, anywhere
149+
const source = `
150+
---
115151
title: Test
116152
---
117153
118154
Some **mdx** text, with a component <Test name={title}/>
119-
`
155+
`
156+
120157
const { content, data } = matter(source)
121158
const mdxSource = await renderToString(content, { components, scope: data })
122159
return { props: { source: mdxSource, frontMatter: data } }
@@ -125,14 +162,18 @@ Some **mdx** text, with a component <Test name={title}/>
125162

126163
Nice and easy - since we get the content as a string originally and have full control, we can run any extra custom processing needed before passing it into `renderToString`, and easily append extra data to the return value from `getStaticProps` without issue.
127164

128-
### Caveats
165+
## Caveats
129166

130-
There's only one caveat here, which is that `import` cannot be used **inside** an mdx file. If you need to use components in your mdx files, they should be provided through the second argument to the `hydrate` and `renderToString` functions.
167+
There's only one caveat here, which is that `import` cannot be used **inside** an MDX file. If you need to use components in your MDX files, they should be provided through the second argument to the `hydrate` and `renderToString` functions.
131168

132169
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.
133170

134-
### Security
171+
## Security
172+
173+
This library evaluates a string of JavaScript on the client side, which is how it hydrates 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 `render-to-string` function to `hydrate`, as instructed in the documentation. **Do not pass user input into `hydrate`.**
174+
175+
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 the `hydrate` function, which can be done using [`unsafe-eval`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#common_sources). It's also worth noting that you do not _have_ to use `hydrate` on the client side, but without it, you will get a server-rendered result, meaning no ability to react to user input, etc.
135176

136-
This library evaluates a string of javascript on the client side, which is how it hydrates 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 `render-to-string` function to `hydrate`, as instructed in the documentation. _Do not pass user input into `hydrate`._
177+
## License
137178

138-
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 the `hydrate` function, which can be done using [`unsafe-eval`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#common_sources). It's also worth noting that you do not _have_ to use `hydrate` on the client side, but without it, you will get a server-rendered result, meaning no ability to react to user input etc.
179+
[Mozilla Public License Version 2.0](./LICENSE)

header.png

28.9 KB
Loading

0 commit comments

Comments
 (0)