Skip to content

Instantly share code, notes, and snippets.

@benawad
Created March 24, 2020 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benawad/20c6c8f21dced3a31401c8eb750f9f62 to your computer and use it in GitHub Desktop.
Save benawad/20c6c8f21dced3a31401c8eb750f9f62 to your computer and use it in GitHub Desktop.
ssg + mdx next.js
import fs from "fs";
import MDX from "@mdx-js/runtime";
import ReactDOM from "react-dom/server";
import path from "path";
const Post = ({ post }) => {
return <div dangerouslySetInnerHTML={{ __html: post }} />;
};
export async function getStaticPaths() {
return {
paths: fs
.readdirSync("posts")
.map(slug => ({ params: { slug: slug.replace(".mdx", "") } })),
fallback: false
};
}
export async function getStaticProps({ params: { slug } }) {
return {
props: {
post: ReactDOM.renderToStaticMarkup(
<MDX>{fs.readFileSync(path.join("posts", slug + ".mdx"))}</MDX>
)
}
};
}
@KriszKecskes
Copy link

KriszKecskes commented Apr 4, 2020

Hi Ben,
I asked about the MDX version on your YouTube channel. First of all, thanks for your quick answer! So, I had the simple MD version now in my experimental project:
https://github.com/KozaKrisz/kozakrisz/blob/master/pages/blog/%5Bslug%5D.tsx

I've just read the warning on the @mdx-js/runtime NPM page:

this is not the preferred way to use MDX since it introduces a substantial amount of overhead and dramatically increases bundle sizes. It should also not be used with user input that isn’t sandboxed.

I am curious about what would be the preffered way? I host my experimental site on Heroku. So that is an SSR rendering project if I understood well the concepts. Would you use @mdx-js/runtime anyway?

Thanks for your answer!

@benawad
Copy link
Author

benawad commented Apr 5, 2020

@mdx-js/runtime won't run in the browser, so should be ok. I haven't looked much into MDX, so there might be a better way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment