Ivan Driuk
Ivan Driuk

Reputation: 13

Why next-auth middleware redirect logged user?

I had made auth with next-auth via Github. After signing in with Github, useSession from next-auth/react on client works correctly. And getServerSession from next-auth/next works correctly. But middleware always redirect (for logged user and for unlogged user).

I'm using Next.js 13 with app router and next-auth 4.

middleware is:

export { default } from 'next-auth/middleware'

export const config = { matcher: ["/path_with_auth1", "/path_with_auth2"] }

Options is:

export const options: NextAuthOptions = {
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),
  ],
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
};

app/api/auth/[...nextauth]/route.ts

import NextAuth from 'next-auth';
import { options } from './options'

const handler = NextAuth(options);

export { handler as GET, handler as POST}

I'm expecting It will redirect only unlogged user. Can you help me? How make it work correctly?

Upvotes: 1

Views: 704

Answers (1)

GN Vageesh
GN Vageesh

Reputation: 370

According to nextAuth documentation, by default the session strategy is set to jwt but when an adapter is provided, it defaults to database

For me setting session strategy to jwt solved the issue.

Your options should now looks like this:

export const options: NextAuthOptions = {
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),
  ],
  session: {
    strategy: "jwt",
  },
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
};

Buy doing this, you are overriding the default strategy from database to jwt since u have provided a adapter

Upvotes: 2

Related Questions