Next.js Discord

Discord Forum

Check if file exists with 'fs' always give error.

Answered
Red wood ant posted this in #help-forum
Open in Discord
Red wood antOP
Im trying to make server to check if file exists, apply logic based on that and move one. I tried to do that in middleware.js using app router logic and got this error:
unhandledRejection: Error: The edge runtime does not support Node.js 'fs' module.


I divided all fs logic into another file and imported in middleware and still i got this error. After searching online for solutions i learned that its impossible to it from middleware.

Next approach was to create route api and try from there and im still getting the same error. I tried multiple approaches to see where function that check if file exists will work and so far find that works only in layout.js.

Is there anyway to check if file exists, this should be easy i dont know why it so complicated?
Answered by Giant panda
Next approach was to create route api and try from there and im still getting the same error.
Route handlers support the fs module as long as they run on Node. If you run it on Edge it won't be available either.
View full answer

5 Replies

Giant panda
Next approach was to create route api and try from there and im still getting the same error.
Route handlers support the fs module as long as they run on Node. If you run it on Edge it won't be available either.
Answer
Red wood antOP
how can i change that?
Red wood antOP
wow thanks after putting
export const runtime = 'nodejs'
in route.js its working, however middleware.js is still not working when i setup that, but nevermind, i can now work with it from endpoint. Thank you very much!!!!
Giant panda
The middleware is always running on Edge, there is no way to change that at all IIRC