next-auth
next-auth copied to clipboard
NextAuth middleware causes infinite redirect if not using Session Strategy
Environment
System: OS: macOS 11.6.8 CPU: (4) x64 Intel(R) Core(TM) i5-4308U CPU @ 2.80GHz Memory: 313.74 MB / 16.00 GB Shell: 4.4.12 - /usr/local/bin/bash Binaries: Node: 16.11.0 - ~/.nvm/versions/node/v16.11.0/bin/node Yarn: 1.9.4 - /usr/local/bin/yarn npm: 8.6.0 - ~/.nvm/versions/node/v16.11.0/bin/npm Watchman: 3.1.0 - /usr/local/bin/watchman Browsers: Chrome: 105.0.5195.125 Safari: 15.6 npmPackages: next: ^12.3.0 => 12.3.0 next-auth: ^4.10.3 => 4.10.3 react: 17.0.2 => 17.0.2
Reproduction URL
https://github.com/nextauthjs/next-auth-example
Describe the issue
Creating a middleware.ts
file without using JWT session strategy causes infinite redirects on protected pages.
How to reproduce
Create a middleware.ts
file with
import { withAuth } from 'next-auth/middleware';
export default withAuth({
pages: {
signIn: '/members/sign-in'
},
});
export const config = { matcher: ['/members/account'] };
And configure your app with a database strategy:
export const authOptions: NextAuthOptions = {
session: {
strategy: "database"
}
...
(forgive me for not forking the example app to demonstrate this, I didn't want to deal with setting up a local db in my fork)
Sign in to the app, then visit the protected page.
This triggers an infinite redirect, which looks like this:

You can see the original call to accounts.json
, which I believe is the getServerSideProps
fetch, triggers the middleware, and NextAuth returns a 307 to log in. Except the sign in page detects that you're already signed in, and redirects you back to where you were, which repeats the infinite redirect.
That's because this line here generates false
for isAuthorized
https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/next/middleware.ts#L141-L142
Which I suspect, but don't know for sure, is from this caveat buried in the docs:
For the time being, the withAuth middleware only supports "jwt" as session strategy.
Maybe this is obvious to other NextAuth users. For me, NextAuth middleware caused a few issues, and while Googling around to try to fix them, I overlooked this caveat. Additionally, I would not an infinite redirect to be the outcome of using the documented middleware.
Expected behavior
I don't know, maybe a warning, or for the protected page to load. Also, this is a surprising limitation, as protecting routes behind login is a core use case of any auth library. Limiting it to only one type of session strategy is not expected.