mikeysee
mikeysee

Reputation: 1763

Access static resource in server-side code in NextJs?

Im using the static render feature of NextJS to generate a static version of my site thus I want to ensure that on the very first render of the page all the data it needs to render correctly is supplied.

I have a number of blog posts which I have stored as .md files in /static and want to access them in a page such as:

import * as fs from "fs";
...

export default class extends React.Component<IProps, any> {

  static async getInitialProps (props: IServerProps) {
    const post = (await getDb()).posts.find(p => p.id == props.query.id);
    const markdown = fs.readFileSync(`/static/posts/${post.markdownFileName}`);
    return { post, markdown }
  }
...

But if try to run the above I get the following error:

This dependency was not found: * fs

So im not sure how I should go about accessing these static resources while on the server..

Upvotes: 2

Views: 1900

Answers (1)

Matt Holland
Matt Holland

Reputation: 2210

Unfortunately Next.js doesn't allow the use of webpack loaders to handle different file types on the server (Although they are used to build the client-side bundles), but it is possible to use a Babel plugin. One such plugin for Markdown content can be found here: https://www.npmjs.com/package/babel-plugin-markdown

After configuring it in .babelrc:

{
  "plugins": ["markdown"]
}

it's possible to use markdown.require() to pull in .md content:

const html = markdown.require('./foo.md')

More options are described at the link!

Upvotes: 1

Related Questions