5

I want to use fs module inside api route file to do some filesystem operations, however, I get this error: Module not found: Can't resolve 'fs' . Not only, I can't use the fs inside my handler function, but also I can't start the project since fs error prevents that.

This is what my file looks like.

Path: pages/api/getSchema.js

Content:

const fs = require("fs");

export default function handler(req, res) {
  const id = req.query.id;
  if(id){
    const schemas = require('../../pageSchemas/index.json');
    res.end(JSON.stringify(schemas[id]));
  }
}

noiseymur
  • 761
  • 2
  • 15
  • Does this answer your question? [Module not found: Can't resolve 'fs' in Next.js application](https://stackoverflow.com/questions/64926174/module-not-found-cant-resolve-fs-in-next-js-application) – derpirscher Oct 29 '22 at 21:52
  • 2
    Unfortunately it doesn't. My problem is, I'm using the fs inside the api route, not a page route, and thus I don't have any of ```getServerSideProps```, ```getStaticProps``` in there – noiseymur Oct 30 '22 at 06:27
  • Are you importing the handler function directly anywhere else? – juliomalves Oct 30 '22 at 22:03
  • @juliomalves No, I don't – noiseymur Oct 31 '22 at 17:16

1 Answers1

0

When I moved the API route to /pages/api it worked

For other errors:

For me this solution worked to solve the fs error but created other errors down the line:

// next.config.js

// For Webpack 4
module.exports = {
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on the `fs` module
    if (!isServer) {
      config.node = {
        fs: 'empty'
      };
    }
  
    return config;
  }
};

// For Webpack 5
module.exports = {
  // Remove the next line for newer versions of Next.js
  webpack5: true,
  webpack: (config) => {
    // Disable fallback for the 'fs' module
    config.resolve.fallback = { fs: false };
  
    return config;
  }
};
Pietro
  • 788
  • 9
  • 8