Next.js 14 App Router中修改HTTP响应状态码的其他实现方式
在Next.js 14 App Router中修改HTTP响应状态码的多种实现方式
背景
在Next.js 14 App Router项目中,因集成了国际化路由,修改特定请求的HTTP响应状态码存在一定复杂度。目前已通过Middleware实现了状态码自定义逻辑,代码如下:
export default async function middleware(request: NextRequest) { const { pathname } = request.nextUrl const handleI18nRouting = createMiddleware({ locales, defaultLocale, localePrefix, localeDetection, pathnames }); let responseLang = handleI18nRouting(request); if (![307, 308].includes(responseLang.status)) { let status = { status: responseLang.status} if(pathname==="path_to_be_validated"){ status.status = 410 } return NextResponse.next({ ...status, headers: responseLang.headers }) } else { return responseLang } }
以下是在页面内部和not-found页面中修改状态码的其他实现方式:
一、页面内部修改状态码(服务器组件)
App Router中仅服务器组件可直接控制HTTP响应状态码,客户端组件无法操作该逻辑。
1. 直接返回自定义Response
在页面组件中,根据业务判断逻辑,直接返回带有指定状态码的Response对象:
export default async function TargetPage() { // 替换为实际业务校验逻辑,比如检查资源是否存在 const resourceExists = await checkResourceStatus(); if (!resourceExists) { // 返回410 Gone状态码及对应提示内容 return new Response("该资源已永久移除", { status: 410 }); } // 正常渲染页面内容 return ( <div> <h1>页面内容</h1> </div> ); }
2. 路由处理函数中返回状态码
针对API路由或动态路由(app/[...path]/route.ts),可直接在HTTP方法处理函数中返回NextResponse并指定状态码:
import { NextResponse } from 'next/server'; export async function GET(request: Request) { const { pathname } = new URL(request.url); if (pathname.includes("path_to_be_validated")) { return new NextResponse(null, { status: 410 }); } return NextResponse.json({ data: "正常响应内容" }); }
二、在not-found页面中修改状态码
默认调用notFound()或访问不存在路径会返回404状态码,若需针对特定路径返回其他状态码(如410),可在自定义not-found.tsx页面中处理:
1. 基于请求路径动态设置状态码
国际化项目中路径会包含locale前缀,可通过headers()获取原始路径信息:
import { headers } from 'next/headers'; export default async function NotFoundPage() { const headersList = headers(); // 获取Next.js传递的原始路径(包含locale) const pathname = headersList.get('x-nextjs-pathname'); // 判断是否为目标路径,返回对应状态码 if (pathname === "/en/path_to_be_validated") { return new Response("资源已永久移除", { status: 410 }); } // 其他情况返回默认404页面 return ( <div> <h1>404 - 页面未找到</h1> </div> ); }
2. 结合Middleware传递状态标识
若需复用Middleware的判断逻辑,可通过自定义Header传递状态标记,再在not-found页面中读取处理:
// Middleware中添加标记逻辑
export default async function middleware(request: NextRequest) { // 原有国际化路由逻辑... if (pathname === "path_to_be_validated") { // 添加自定义Header标记状态码 responseLang.headers.set('x-custom-status', '410'); } // ... }
// not-found.tsx中读取Header并返回对应状态
import { headers } from 'next/headers'; export default async function NotFoundPage() { const statusHeader = headers().get('x-custom-status'); if (statusHeader === '410') { return new Response("资源已永久移除", { status: 410 }); } return <h1>404 - 页面未找到</h1>; }
内容的提问来源于stack exchange,提问作者Joshua Joel Cleveland
相关产品推荐
相关产品推荐

