【问题标题】:Next.js: _Middleware with NextResponse blocks images from renderingNext.js:带有 NextResponse 的 _Middleware 阻止图像渲染
【发布时间】:2022-07-30 00:47:12
【问题描述】:
这个问题延伸到this question。 Next.js 中带有import { NextResponse } from "next/server"; 的 _middleware 可用于 JWT 身份验证,但会阻止包括图像在内的所有路由。这意味着如果您有想要通过 CSS 或 Image 在重定向路由中加载的图像,则不会加载。下面的代码阻止地址栏重定向并允许加载图像。访问令牌可能会更好
【问题讨论】:
标签:
authentication
routes
path
next.js
jwt
【解决方案1】:
更新:经过一些调试,这就是我想出的。我之前写的代码不会让你在登录后被重定向到主页。原因是 _Middleware 似乎在 /api/login 之前运行并且基于 prev 条件,只是将它们再次重定向到登录并返回 void(_Middleware “包含”重定向)。
此更新后的代码允许在没有刷新令牌的情况下路由 /api/login,如果他们在没有令牌的情况下通过地址栏导航,则将它们发送回登录
import { NextResponse } from "next/server";
export default function (req: {
url?: any;
cookies?: any;
}): void | NextResponse {
const { cookies } = req;
const url: string = req.url;
const refreshToken: string | undefined = cookies?.refresh_token_extreme;
const baseUrl: string = "http://localhost:3000";
// vercel.svg is used in /login
const unprotectedPaths: string[] = [
`${baseUrl}/login`,
`${baseUrl}/favicon.ico`,
`${baseUrl}/vercel.svg`,
`${baseUrl}/_next/webpack-hmr`,
`${baseUrl}/attachables/campus-images/image1.jpg`,
`${baseUrl}/attachables/mnhs-images/logos/login_logo.png`,
`${baseUrl}/attachables/mnhs-images/logos/mnhs_favicon_og.ico`,
]
if (unprotectedPaths.includes(url)) {
return void 0;
} else if (!refreshToken && url === "http://localhost:3000/api/login") {
return NextResponse.next();
} else if (!refreshToken) {
return NextResponse.redirect(`${baseUrl}/login`);
} else {
return NextResponse.next();
}
}
【解决方案2】:
将为项目中的每个路由调用中间件。以下是执行顺序:
- 来自 next.config.js 的标头
- 从 next.config.js 重定向
- 中间件(重写、重定向等)
- 来自 next.config.js 的 beforeFiles(重写)
- 文件系统路由(public/、_next/static/、Pages 等)
- 来自 next.config.js 的 afterFiles(重写)
- 动态路由 (/blog/[slug])
- 从 next.config.js 回退(重写)
有两种方法可以定义中间件将在哪些路径上运行:
Custom matcher config
Conditional statements
for more informations