Next.js Discord

Discord Forum

Module not found: Can't resolve 'fs'

Answered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
Hi. I'm having an issue with one of my components that uses 'fs' to read files from directories. The error happens inside my getStaticProps() function. The error I'm getting (also attached screenshot):
NOTE: When making the component its own page, everything works fine, but I need it as a component.

./Components/SearchBar.jsx:9:0
Module not found: Can't resolve 'fs'
7 | import { useState, useEffect } from "react";
8 |
9 | import fs from "fs";
10 | import path from "path";
11 | import matter from "gray-matter";
12 |

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./pages/_app.js

I researched online and recent posts are saying it has something to do with using 'fs' in the client side vs server side. I'm not fully understanding, could someone help fix this error please.
Answered by Arinji
you cant import fs in a client component
View full answer

10 Replies

you cant import fs in a client component
Answer
you can in a server component
thats a massive security risk if ppl can just access your fs lol since client components are sent to the client
@Arinji you cant import fs in a client component
Sloth bearOP
I see, so for this solution I should use 'fs' in a server component like a page and then pass the data to the client component. Thank you for replying.
yup
btw pro tip, use fs/promises.. you can then await it :D
Original message was deleted
Sloth bearOP
I have it installed, the issue seems to be that using 'fs' is dangerous on the client component.
@Arinji btw pro tip, use fs/promises.. you can then await it :D
Sloth bearOP
Cool thank you 🙂
@Sloth bear Cool thank you 🙂
Asiatic Lion
If I were you, I would have marked Arinji's as a solution.
@Asiatic Lion If I were you, I would have marked Arinji's as a solution.
Sloth bearOP
Sry I'm dumb, new to this