Next.js Discord

Discord Forum

Next Auth Middleware - The Token is always empty.

Answered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
import { withAuth } from "next-auth/middleware";

// middleware is applied to all routes, use conditionals to select

export default withAuth(function middleware(req) {}, {
  callbacks: {
    authorized: ({ req, token }) => {
      console.log("authorized", token);
      if (req.nextUrl.pathname.startsWith("/dashboard") && token === null) {
        return false;
      }
      return true;
    },
  },
  pages: {
    signIn: "/auth/signin",
  },
});

I have this middleware to protect dashboard routes, but the token is always null for some reason.

Even if I am logged in.

I searched for the issue, but couldn't find any answers.
Answered by American black bear
After some more browsing, I solved this issue.

The problem was that when we use the adapter (I used Prisma), the strategy is by default database, but middleware doesn't work with database strategy.

So I changed strategy to jwt.
 session: {
    strategy: "jwt",
  },


It's working completely fine now.
View full answer

2 Replies

American black bearOP
After some more browsing, I solved this issue.

The problem was that when we use the adapter (I used Prisma), the strategy is by default database, but middleware doesn't work with database strategy.

So I changed strategy to jwt.
 session: {
    strategy: "jwt",
  },


It's working completely fine now.
Answer
American black bearOP