nextjs-16-proxy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNext.js 16 Proxy Convention
Next.js 16 代理约定
Next.js 16 renamed to to better reflect its network boundary purpose.
middlewareproxyNext.js 16 将重命名为,以更准确地体现其网络边界的作用。
middlewareproxyKey Changes from Middleware
与旧版中间件的主要变化
| Old (Next.js 15) | New (Next.js 16+) |
|---|---|
| |
| |
| Same location | Same location |
| Next.js 15(旧版) | Next.js 16+(新版) |
|---|---|
| |
| |
| 位置不变 | 位置不变 |
File Location
文件位置
Place at the same level as or :
proxy.tsapppagessrc/
├── proxy.ts ← Correct location
├── app/
│ └── ...NOT inside :
app/src/
├── app/
│ ├── proxy.ts ← Wrong location
│ └── ...将放置在与或同级的目录下:
proxy.tsapppagessrc/
├── proxy.ts ← 正确位置
├── app/
│ └── ...不要放在目录内:
app/src/
├── app/
│ ├── proxy.ts ← 错误位置
│ └── ...Basic Template
基础模板
typescript
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Example: rewrite /uploads/* to /api/uploads/*
if (pathname.startsWith("/uploads/")) {
const newUrl = request.nextUrl.clone();
newUrl.pathname = pathname.replace("/uploads/", "/api/uploads/");
return NextResponse.rewrite(newUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/uploads/:path*"],
};typescript
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// 示例:将/uploads/*重写为/api/uploads/*
if (pathname.startsWith("/uploads/")) {
const newUrl = request.nextUrl.clone();
newUrl.pathname = pathname.replace("/uploads/", "/api/uploads/");
return NextResponse.rewrite(newUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/uploads/:path*"],
};Common Issue: Dynamic Routes Catching Paths
常见问题:动态路由捕获路径
When you have a dynamic route like at the root, it can catch paths before rewrites in are applied.
[teamSlug]next.config.tsProblem:
- Request:
/uploads/image.png - Dynamic route catches it as
[teamSlug]teamSlug = "uploads" - Results in 404
Solution:
Use instead of rewrites. Proxy runs before routing.
proxy.tsnext.config.ts当你在根目录有一个类似的动态路由时,它可能会在中的重写规则生效前捕获路径。
[teamSlug]next.config.ts问题:
- 请求:
/uploads/image.png - 动态路由会将其捕获为
[teamSlug]teamSlug = "uploads" - 导致404错误
解决方案:
使用替代中的重写规则。Proxy会在路由匹配之前运行。
proxy.tsnext.config.tsMigration Command
迁移命令
bash
npx @next/codemod@canary middleware-to-proxy .This automatically:
- Renames →
middleware.tsproxy.ts - Updates function name →
middlewareproxy
bash
npx @next/codemod@canary middleware-to-proxy .该命令会自动执行以下操作:
- 将重命名为
middleware.tsproxy.ts - 将函数名更新为
middlewareproxy