Saturday, 1 April 2023

next-auth error: "Can't resolve module 'next/headers'"

The Issue

Recently I've been working on a site using Sitecore headless (JSS) with authentication. As we're using Next.JS it makes the most sense to utilise NextAuth.JS which has been around for a while, has super easy setup, and integrates with loads of providers - including a couple which we needed for the project.

Everything seemed to be working well, until we started using getServerSession() to fetch the session info server-side, when everything started to fall apart in errors - particularly one mentioning:

Can't resolve module 'next/headers'
A quick search led to a few results such as issue 6559 which indicated we may need to revert to version 4.15.1 (we were using the latest, 4.20.1). This did indeed appear to get around that particular error, though we weren't sure at what cost (and we weren't about to go looking through the change history between those 2 versions). 

Instead I made a small git repo with a minimal reproduction of the issue (all JSS mocked out), logged issue #7103 on the next-auth github repo, and surprisingly heard back from one of the authors within 24 hours with a workaround. Not as good as a fix, of course, but it unblocked us which is definitely a great outcome!

The Fix

Checkout my branch patch-fix for pre-fixed version.

Perform the following steps in your local project:

npm install --save-dev patch-package

Remove the 'if' block from packages/next-auth/src/next/index.ts#L121-L139 leaving just the 'else' lines packages/next-auth/src/next/index.ts#L136-L138.

npx patch-package next-auth

This should resolve the issue for anyone else using the repo!

Note: Please keep in mind this is only relevant for Next.JS v12 (not v13) - see the comment from balazorban44 in the issue

No comments:

Post a Comment