Nextjs How to move custom folder to production on Vercel

Viewed 214

I have recently started development on the NextJS environment. in my project, I have some JSON files inside a folder in my root directory, and I read the content of those files inside my code. it works well on my local machine, but when it goes to production on vercel server, it can't read the file because the file doesn't exist on the server.

here is my project file structure in local machin:

|--.next
|--components
|--jsonfiles
|--node_modules
|--pages
|--public
|--package.json

(and more)...

but after deployment when I read the content of root directory using fs.readdirSync("./") it only contains the following files and directories:

|--.next
|--___next_launcher.js
|--___vc_bridge.js
|--node_modules
|--package.json

and here is my code for reading the file:

   const fs = require('fs');
   const rawcontent = fs.readSync('./jsonfiles/list.json');
   const list:array[] = JSON.parse(rawcontent);
   ...

Any solution for this problem?

1 Answers

Vercel relies on some internal magic with module substitution/enrichment done by NextJS. E.g if you import path synchronously you can control which folders will be readable on Vercel. Sounds weird but it's true!

export async function getStaticProps() {
  const path = await import("path").then(m => m.default) // won't be bundled
  path.resolve("content") // works, does nothing
  return {props: {}}
}

vs

import "path" // won't be bundled unless used outside of SSR hooks

export async function getStaticProps() {
  path.resolve("content") // works, does nothing, makes "content" accessible to lambdas on Vercel 
  return {props: {}}
}

More details here: https://github.com/vercel/vercel/discussions/7971

Related