Skip to content

How to fix the `can't resolve module` error in Next.js

New Course Coming Soon:

Get Really Good at Git

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: