home ~ projects ~ socials

Read A Local File In Nextjs

This is done with getStaticProps which happens on the server side

export default function Page({fileAsString}) {
      return <div>{fileAsString}</div>
  }

  export async function getStaticProps(context) {
    try {
      const fileText = fs.readFileSync(
        `./pages/switch-components-via-state.js`,
        `utf8`
      )
      return {
        props: {
          fileAsString: fileText,
        },
      }
    } catch (err) {
      console.log(err)
      return {
        props: {
          fileAsString: `could not find file`,
        },
      }
    }
  }

Note that in the node docs fs is included via const fs = require('fs') but here it's done with import fs from 'fs'

-- end of line --