You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js 12中间件中获取Next-Auth会话并进行角色/认证校验

How to Retrieve NextAuth Session/User in Next.js Middleware (NextRequest)

I’ve faced this exact issue before! The problem is that getSession from next-auth/client is designed to work with NextApiRequest (the request object in API routes), but Next.js middleware uses NextRequest, which has a different structure. Here’s how to fix it using NextAuth’s JWT utilities:

Solution: Use getToken from next-auth/jwt

Instead of relying on getSession, you can directly parse the JWT cookie that NextAuth uses to store session data. This works seamlessly with NextRequest in middleware.

Step 1: Update Your Middleware Code

Replace your existing middleware with this code:

import { getToken } from "next-auth/jwt";
import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";

async function middleware(req: NextRequest, ev: NextFetchEvent) {
  // Fetch the JWT token from request cookies
  const token = await getToken({
    req,
    secret: process.env.NEXTAUTH_SECRET, // Ensure this matches your NextAuth secret
  });

  // Check if user is authenticated
  if (!token) {
    return new Response("Auth required", {
      status: 401,
      headers: {
        "WWW-Authenticate": 'Basic realm="Secure Area"',
      },
    });
  }

  // Access user data from the token (customize based on your session setup)
  const user = {
    id: token.id,
    email: token.email,
    name: token.name,
    role: token.role, // Include this if you track user roles
  };

  // Example: Role-based authorization check
  if (user.role !== "admin") {
    return new Response("Forbidden: Admin access required", { status: 403 });
  }

  // Proceed with the request if all checks pass
  return NextResponse.next();
}

export { middleware };

Step 2: Configure NextAuth for JWT (If Not Already Done)

This approach relies on the JWT session strategy. Ensure your pages/api/auth/[...nextauth].ts config uses JWT and includes the necessary callbacks to attach user data to the token:

import NextAuth from "next-auth";
import { YourProvider } from "next-auth/providers"; // Replace with your actual provider(s)

export default NextAuth({
  secret: process.env.NEXTAUTH_SECRET,
  providers: [
    YourProvider({
      // Provider configuration
    }),
  ],
  session: {
    strategy: "jwt", // Critical for this middleware approach
  },
  callbacks: {
    async jwt({ token, user }) {
      // Attach user data to the JWT when the user logs in
      if (user) {
        token.id = user.id;
        token.role = user.role; // Add any custom fields you need
      }
      return token;
    },
    async session({ session, token }) {
      // Sync JWT data with the session object (for API routes/pages)
      session.user.id = token.id;
      session.user.role = token.role;
      return session;
    },
  },
});

Key Notes:

  • Performance: Using JWT avoids database calls in middleware, which keeps your requests fast. If you were using the database session strategy, switching to JWT is recommended for middleware use.
  • Secret: Make sure NEXTAUTH_SECRET is set in your .env file and matches across your NextAuth config and middleware.
  • Custom Fields: Add any user-specific data (like roles) to the JWT via the jwt callback so it’s accessible in middleware.

内容的提问来源于stack exchange,提问作者Maruf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:32:42