Search code examples
node.jsnext.jsnode-modulesmodule.exports

Nodejs (Next) Cannot import object from module: Module not found: Can't resolve 'fs'


I have nodejs app using react and nextjs. The most important pieces of the app are kept in the server file.

main.js(server file)

const app = next({ dev }) //dev = true

...

const DR_LINK = "anything"

module.exports.app = app;
module.exports.DR_LINK = DR_LINK;

Now I need the app object for some of my routers.

//any router file
const {app} = require("../main")

And it works perfectly fine. But when I try to import the string DR_LINK object

import {DR_LINK} from "../main"; 
//not in the same file as the import for app

I get this error

error - ./node_modules/destroy/index.js:14:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/send/index.js
./node_modules/express/lib/response.js
./node_modules/express/lib/express.js
./node_modules/express/index.js
./main.js
./components/CreateForm.js
./pages/create.js

https://nextjs.org/docs/messages/module-not-found
error - unhandledRejection: OverwriteModelError: Cannot overwrite `Declaration` model once compiled.
//for some reason it affects the db models too

The export order or exporting it like

module.exports = { app, DR_LINK}; 

makes not difference. The app is allways exported but the string object is not. This only happens when app object is exported in any way from the server file. By removing it, everything works fine.


Solution

  • I think you are mixing up server side and client side code. My guess is you are trying to doimport {DR_LINK} from "../main"; on client side from a server file. The clue is the error Module not found: Can't resolve 'fs'. This is because fs is a built in node.js (server side) package, so your frontend will not know what it is.

    I suspect your router files are still server side, hence why the imports (require) work there.

    You can define env variables inside next config like so:

    https://nextjs.org/docs/api-reference/next.config.js/environment-variables

    Or maybe this could also be an option for you as well:

    https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser