How to fix the `can't resolve module` error in Next.js
I ran into this issue with Next.js:
Module not found: Can’t resolve ‘fs’
In a Next.js page your can import methods from a file that loads Node.js modules.
This is fine, as long as you also use the imported method in getStaticProps().
Example, I had this code:
import { getData } from '../lib/data'
//...
export async function getStaticProps() {
const data = getData()
return {
props: {
data,
},
}
}
When I commented const data = getData()
, Next started giving me the error 'fs' module not found
because fs
was the first module I imported in lib/data
.
It might happen with any other Node library you import first.
This happens because anything in getStaticProps() is just called when ran in a server environment, but if we don’t invoke the Node.js function in there, Next.js can’t know that.
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025