the edge runtime does not support Node.js crypto module, only in middleware Edge Runtime
Build fails with:
Error: The edge runtime does not support Node.js 'crypto' module.
Learn more: https://nextjs.org/docs/messages/node-module-in-edge-runtime
It only happens for middleware.ts. The same import in a route handler is fine. All middleware does is read a session cookie and redirect to /login when it is missing - it does not knowingly touch crypto at all. The import chain goes middleware -> @/lib/auth -> a session helper -> jsonwebtoken.
Next 15.3. Do I need to give up on checking the session in middleware, or is there a shape that works?
@cast_iron_carl · 2d ago · 3 replies
Swap
jsonwebtokenforjoseand the error goes away.joseis built on Web Crypto, which the edge runtime does have, and verify looks like this:The deeper fix is the import chain.
@/lib/authalmost certainly also pulls in your database client and a password hashing library, and middleware runs on every matched request including static assets if your matcher is sloppy. Make a separatelib/auth-edge.tsthat contains only cookie reading and token verification, import that from middleware, and keep the fat one for route handlers.Reply
Report
@cast_iron_carl · 2d ago
Make the edge one the primitive and have the Node one import it.
auth-edge.tsexportsreadSessionToken(cookies)andverify(token);auth.tsimports both and adds the database lookup on top. One implementation, two entry points, and the fat one can never accidentally leak into the thin one because the dependency only points one way.Reply
Report
@duckweed_dev · 16h ago
The split file worked. Slightly worried about having two places that know how to read a session - is there a way to keep them from drifting apart?
Reply
Report