突然,我的中间件在部署中停止了工作.错误是:
> Build error occurred
NestedMiddlewareError: Nested Middleware is not allowed, found:
pages/_middleware
Please move your code to a single file at /middleware instead.
Vercel语句是:例如,位于pages/about/u中间件的中间件.ts可以将逻辑移动到/中间件.在存储库的根目录中.然后,条件语句只能用于在与about/*路径匹配时运行中间件:
当我使用pages/u中间件运行本地构建时.ts它完成时没有任何错误,就像今天生产时一样.如果我将其更改为页面/中间件.ts局部故障:
./pages/middleware.ts
2:1 Error: next/server should not be imported outside of pages/_middleware.js. See: https://nextjs.org/docs/messages/no-server-import-in-page @next/next/no-server-import-in-page
中间件文件:
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(req: NextRequest, res: NextResponse) {
if (req.nextUrl.pathname === "/") {
const session = await getToken({
req,
secret: process.env.JWT_SECRET,
secureCookie: process.env.NODE_ENV === "production",
});
// You could also check for any property on the session object,
// like role === "admin" or name === "John Doe", etc.
if (!session) {
const url = req.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
// If user is authenticated, continue.
}
}