Skip to content

Commit

Permalink
Merge pull request #2 from hashicorp/main
Browse files Browse the repository at this point in the history
Update from original package
  • Loading branch information
Howard86 authored Feb 26, 2021
2 parents 81ef6e2 + 7f128a4 commit df63d23
Show file tree
Hide file tree
Showing 22 changed files with 3,795 additions and 2,302 deletions.
24 changes: 24 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
version: 2.1

orbs:
node: circleci/[email protected]
puppeteer: threetreeslight/[email protected]

jobs:
run-tests:
environment:
NODE_ENV: development
docker:
- image: circleci/node:latest-browsers
steps:
- checkout
- node/install-packages
- puppeteer/install
- run:
name: Run tests
command: npm test

workflows:
test:
jobs:
- run-tests
4 changes: 3 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
__tests__
examples
.prettierrc
.prettierrc
tsconfig.json
babel.config.js
127 changes: 117 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ export async function getStaticProps() {
}
```

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.
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 it uses only on the server, so `renderToString` will be removed from the browser bundle entirely.

## APIs

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.

- **`renderToString(source: string, { components?: object, mdxOptions?: object, scope?: object })`**
- **`renderToString(source: string, { components?: object, mdxOptions?: object, provider?: object, scope?: object })`**

**`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.

Expand All @@ -86,24 +86,27 @@ This library exposes two functions, `renderToString` and `hydrate`, much like `r
// Optional parameters
{
// The `name` is how you will invoke the component in your MDX
components: { name: React.ComponentType },
components?: { name: React.Component },
// wraps the given provider around the mdx content
provider?: { component: React.Component, props: Record<string, unknown> },
// made available to the arguments of any custom mdx component
scope?: {},
// MDX's available options at time of writing pulled directly from
// https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js
mdxOptions: {
mdxOptions?: {
remarkPlugins: [],
rehypePlugins: [],
hastPlugins: [],
compilers: [],
filepath: '/some/file/path',
},
scope: {},
}
)
```

Visit <https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js> for available `mdxOptions`.

- **`hydrate(source: object, { components?: object })`**
- **`hydrate(source: object, { components?: object, provider?: object })`**

**`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.

Expand All @@ -114,6 +117,7 @@ This library exposes two functions, `renderToString` and `hydrate`, much like `r
// Should be the exact same components that were passed to `renderToString`
{
components: { name: React.ComponentType },
provider: { component: React.ComponentType, props: Record<string, unknown> },
}
)
```
Expand Down Expand Up @@ -146,8 +150,7 @@ export default function TestPage({ source, frontMatter }) {
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source = `
---
const source = `---
title: Test
---

Expand All @@ -162,7 +165,48 @@ Some **mdx** text, with a component <Test name={title}/>

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.

## Caveats
### Using Providers

If any of the components in your MDX file require access to the values from a provider, you need special handling for this. Remember, this library treats your mdx content as _data provided to your page_, not as a page itself, so providers in your normal scope will not naturally wrap its results.

Let's look at an example of using an auth0 provider, so that you could potentially customize some of your mdx components to the user viewing them.

```jsx
import { Auth0Provider } from '@auth0/auth0-react'
import renderToString from 'next-mdx-remote/render-to-string'
import hydrate from 'next-mdx-remote/hydrate'
import Test from '../components/test'
const components = { Test }
// here, we build a provider config object
const provider = {
component: Auth0Provider,
props: { domain: 'example.com', clientId: 'xxx', redirectUri: 'xxx' },
}
export default function TestPage({ source }) {
const content = hydrate(source, { components, provider }) // <- add the provider here
return <div className="wrapper">{content}</div>
}
export async function getStaticProps() {
// mdx text - can be from a local file, database, anywhere
const source = 'Some **mdx** text, with a component <Test />'
const mdxSource = await renderToString(source, { components, provider }) // <- add it here as well
return { props: { source: mdxSource } }
}
```

That's it! The provider will be wrapped around your MDX page when hydrated and you will be able to be able to access any of its values from within your components. For an example using a custom provider, check out the test suite.

### How Can I Build A Blog With This?

Data has shown that 99% of use cases for all developer tooling are building unnecessarily complex personal blogs. Just kidding. But seriously, if you are trying to build a blog for personal or small business use, consider just using normal html and css. You definitely do not need to be using a heavy full-stack javascript framework to make a simple blog. You'll thank yourself later when you return to make an update in a couple years and there haven't been 10 breaking releases to all of your dependencies.

If you really insist though, check out [our official nextjs example implementation](https://github.com/vercel/next.js/tree/canary/examples/with-mdx-remote). 💖

### Caveats

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.

Expand All @@ -172,7 +216,70 @@ Hopefully this makes sense, since in order to work, imports must be relative to

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`.**

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.
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).

### Usage Without Hydration

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. To do this, pass the `renderedOutput` prop of the object returned by `renderToString` to [`dangerouslySetInnerHTML`](https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml):

```jsx
import renderToString from 'next-mdx-remote/render-to-string'
import Test from '../components/test'
const components = { Test }
export default function TestPage({ renderedOutput }) {
return (
<div
className="wrapper"
dangerouslySetInnerHTML={{ __html: renderedOutput }}
/>
)
}
export async function getStaticProps() {
// <Test /> will be rendered to static markup, but will be non-interactive!
const source = 'Some **mdx** text, with a component <Test />'
const { renderedOutput } = await renderToString(source, { components })
return { props: { renderedOutput } }
}
```

## Typescript

This project does include native types for typescript use. Both `renderToString` and `hydrate` have types normally as you'd expect, and the library also offers exports of two types that are shared between the two functions and that you may need to include in your own files. Both types can be imported from `next-mdx-remote/types` and are namespaced under `MdxRemote`. The two types are as follows:

- `MdxRemote.Components` - represents the type of the "components" object referenced in the docs above, which needs to be passed to both `hydrate` and `renderToString`
- `MdxRemote.Source` - represents the type of the return value of `renderToString`, which also must be passed into `hydrate.
Below is an example of a simple implementation in typescript. You may not need to implement the types exactly in this way for every configuration of typescript - this example is just a demonstration of where the types could be applied if needed.
```ts
import renderToString from 'next-mdx-remote/render-to-string'
import hydrate from 'next-mdx-remote/hydrate'
import { MdxRemote } from 'next-mdx-remote/types'
import ExampleComponent from './example'

const components: MdxRemote.Components = { ExampleComponent }

interface Props {
mdxSource: MdxRemote.Source
}

export default function ExamplePage({ mdxSource }: Props) {
const content = hydrate(mdxSource, { components })
return <div>{content}</div>
}

export async function getStaticProps() {
const mdxSource = await renderToString(
'some *mdx* content: <ExampleComponent />',
{ components }
)
return { props: { mdxSource } }
}
```
## License
Expand Down
2 changes: 2 additions & 0 deletions __tests__/fixtures/basic/mdx/test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ name: jeff

<Test name={name} />

<ContextConsumer />

Some **markdown** content

~> Alert
30 changes: 29 additions & 1 deletion __tests__/fixtures/basic/pages/index.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,48 @@
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import { createContext, useEffect, useState } from 'react'
import renderToString from '../../../../render-to-string'
import hydrate from '../../../../hydrate'
import Test from '../components/test'
import { paragraphCustomAlerts } from '@hashicorp/remark-plugins'

const TestContext = createContext('test')
const PROVIDER = {
component: TestContext.Provider,
props: { value: 'foo' },
}
const MDX_COMPONENTS = {
Test,
ContextConsumer: () => {
return (
<TestContext.Consumer>
{(value) => <p className="context">Context value: "{value}"</p>}
</TestContext.Consumer>
)
},
strong: (props) => <strong className="custom-strong" {...props} />,
}

export default function TestPage({ data, mdxSource }) {
const [providerOptions, setProviderOptions] = useState(PROVIDER)

useEffect(() => {
setProviderOptions({
...PROVIDER,
props: {
value: 'bar',
},
})
}, [])

return (
<>
<h1>{data.title}</h1>
{hydrate(mdxSource, { components: MDX_COMPONENTS })}
{hydrate(mdxSource, {
components: MDX_COMPONENTS,
provider: providerOptions,
})}
</>
)
}
Expand All @@ -25,6 +52,7 @@ export async function getStaticProps() {
const { data, content } = matter(fs.readFileSync(fixturePath, 'utf8'))
const mdxSource = await renderToString(content, {
components: MDX_COMPONENTS,
provider: PROVIDER,
mdxOptions: { remarkPlugins: [paragraphCustomAlerts] },
scope: data,
})
Expand Down
Loading

0 comments on commit df63d23

Please sign in to comment.