Next 13以上版本 App Router middleware中间件不生效

329 阅读1分钟

1. 与文件位置有关

1.1 如果有src目录 将middleware.ts放在src目录下
1.2. 如果没有就放在根目录下
1.3. 中间件的导出方式,使用export function,不允许用default
1.4. 注意:middleware 只能是服务端内容,不可写客户端组件内容
    // middleware.ts
    import { NextResponse } from 'next/server'
    import type { NextRequest } from 'next/server'
    const PROTECTED_ROUTES = ['/my-creations']
    import {ACCESS_TOKEN} from '@base/const'
    
    console.log("正在执行 middleware 的内容")

    export function middleware(request: NextRequest) {
        if (PROTECTED_ROUTES.includes(request.nextUrl.pathname)) {
            return NextResponse.redirect(new URL('/login', request.url))
        }
    }

    // 设置路径匹配规则
    export const config = {
        matcher: PROTECTED_ROUTES,
    }

2. 如果 middleware 的位置、代码都没有问题的话,可能是 next.config.ts阻止了middleware的执行,可以将一些配置注视掉再查看是否有效

import type { NextConfig } from 'next';

/** @type {import('next').NextConfig} */
const nextConfig: NextConfig = {
    // 禁用开发时的源码映射
    productionBrowserSourceMaps: false,

    // 优化构建输出
    output: 'standalone',

    // swcMinify 现在是默认启用的,不需要显式禁用
    reactStrictMode: false,

};

export default nextConfig;