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

Next.js中next-auth的middleware.ts未触发,受保护路由可无权限访问

解决Next.js App Router中next-auth middleware未触发的问题

核心问题定位

你的middleware.ts里withAuth配置的authorized回调直接返回true,这会让next-auth跳过所有认证检查,直接放行所有请求,导致自定义的middleware逻辑完全不执行。

修复步骤

1. 移除错误的authorized回调

删除withAuth配置中的callbacks.authorized,让next-auth默认处理认证状态,或者根据需求自定义授权逻辑:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { withAuth } from 'next-auth/middleware';
import { getToken } from 'next-auth/jwt';
    
export default withAuth(
  async function middleware(request: NextRequest) {
    console.log('⛔️ Middleware triggered for:', request.nextUrl.pathname);     
    const pathname = request.nextUrl.pathname;
    const isAuth = await getToken({ req: request });
        
    const protectedRoutes = ['/profile', '/admin'];
    const isProtectedRoute = protectedRoutes.some(route => pathname.startsWith(route));
    const isAuthRoute = pathname.startsWith('/auth/signin') || pathname.startsWith('/auth/signup');
    
    if (!isAuth && isProtectedRoute) {
        return NextResponse.redirect(new URL('/auth/signin', request.url));
    }
    
    // 已认证用户禁止访问登录/注册页
    if (isAuth && isAuthRoute) {
        return NextResponse.redirect(new URL('/home', request.url));
    }
    
    return NextResponse.next();
}
);
    
export const config = {
  matcher: ['/profile/:path*', '/admin/:path*', '/auth/:path*'],
};

2. 验证文件位置与matcher配置

  • 确保middleware.ts(或.js)放在项目根目录(和app文件夹同级),不要放在app目录内部。
  • 确认config.matcher覆盖了所有需要拦截的路由,若有其他受保护路由,补充到数组中即可。

3. 检查依赖版本兼容性

你使用的是Next.js 15.3.4,需确保next-auth版本与Next.js版本匹配,执行以下命令更新依赖:

npm install next-auth@latest
# 或使用pnpm/yarn
pnpm add next-auth@latest
yarn add next-auth@latest

4. 清除缓存并重启开发服务器

Next.js开发服务器可能缓存旧的middleware代码,执行以下操作:

  • 停止开发服务器
  • 删除项目根目录下的.next文件夹
  • 重新启动服务器:npm run dev

额外优化建议

可以简化逻辑,直接利用withAuth的内置能力处理重定向,无需手动调用getToken:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { withAuth } from 'next-auth/middleware';

export default withAuth(
  function middleware(request: NextRequest) {
    console.log('⛔️ Middleware triggered for:', request.nextUrl.pathname);
    // 已认证用户访问登录/注册页时重定向到首页
    if (request.nextUrl.pathname.startsWith('/auth/signin') || request.nextUrl.pathname.startsWith('/auth/signup')) {
      return NextResponse.redirect(new URL('/home', request.url));
    }
  },
  {
    callbacks: {
      // 未认证时自动重定向到登录页
      authorized: ({ token }) => !!token,
    },
    pages: {
      signIn: '/auth/signin',
    },
  }
);

export const config = {
  matcher: ['/profile/:path*', '/admin/:path*', '/auth/:path*'],
};

内容的提问来源于stack exchange,提问作者Maryem Hadj Wannes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:27:34