NextJS 全局中间件-校验权限

Posted by CodingWithAlice on March 2, 2025

NextJS 全局中间件-校验权限

总结

  • middleware.ts 的路径是和app 同层级,src/middleware.ts 下面
  • 中间件利用 NextRequest 和 NextResponse 处理逻辑操作
  • 路由匹配器:匹配在哪些路由上生效 matcher: '/api/:path*'

Nextjs 官方文档 - 中间件

实现对 Nextjs 全局的 api 接口的权限校验

Step1:在项目根目录中创建 middleware.ts ,和 app 一个同级,即src/middleware.ts

Step2:声明各个中间件功能 - 权限校验

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export const config = {
    matcher: '/api/:path*', // 匹配 api 下所有接口
}

export function middleware(request: NextRequest) {
	if(request.method === 'POST') {
        const auth = request.headers.get('Authorization')
        if (!auth || auth !== process.env.CHECK_AUTH) {
			return NextResponse.json({ message: '达咩' }, { status: 401 })
		}
    }
    return NextResponse.next()
    // return NextResponse.redirect(new URL('/home', request.url))
}

Step3:在哪些路径上运行

  • 匹配器规则:必须以 / 开头;可以包含命名参数 /api/:path;修饰符 * + ? 正则 (.*)
export const config = {
  matcher: '/api/:path*', // 特定路径
}
// ① 匹配多个路径 matcher: ['/about/:path*', '/dashboard/:path*']
/** ② 通过 has 和 missing 关键词绕过某些请求的中间件
matcher: [{
	source:'/((?!api|_next/static|_next/image|sitemap.xml|robots.txt).*)',
	has: [{ type: 'header', key: 'x-present' }],
	missing: [{ type: 'header', key: 'x-missing', value: 'prefetch' }],
}] */