Next.js 13.5如何设置页面HTTP 503状态码?
解决Next.js 13.5设置503状态码+自定义错误页的方案
方案一:App Router页面组件直接返回503响应(推荐)
在目标页面组件中,当判断需要返回503时,直接返回带有自定义页面内容的NextResponse,同时指定状态码,既保证HTTP状态正确,又能渲染自定义错误界面。
修改你的页面组件代码如下:
import { NextResponse } from 'next/server'; import ReactDOMServer from 'react-dom/server'; import capitalizeFirstLetter from './path-to-your-capitalize-function'; // 替换为你的函数实际路径 const StatePage = async ({ params }) => { const state = capitalizeFirstLetter(params.state); const states = [ "Federal", "Ontario", "Quebec", "Nova-Scotia", "Saskatchewan", "Newfoundland-and-Labrador", "New-Brunswick", "Manitoba", "Prince-Edward-Island", "Yukon", "Northwest-Territories", "British-Columbia", "Alberta", ]; if (states.includes(state)) { // 自定义503错误组件 const Custom503 = () => ( <div className="flex flex-col items-center justify-center h-screen"> <h1>503 服务暂时不可用</h1> <p>该页面正在维护中,请稍后再试</p> </div> ); // 将组件转为HTML字符串,保留样式支持 const componentHtml = ReactDOMServer.renderToString(<Custom503 />); const fullHtml = ` <!DOCTYPE html> <html> <head> <title>503 服务不可用</title> <link rel="stylesheet" href="/styles/global.css"> <!-- 替换为你的全局样式路径 --> </head> <body>${componentHtml}</body> </html> `; return new NextResponse(fullHtml, { status: 503, headers: { 'Content-Type': 'text/html; charset=utf-8', }, }); } else { // 无匹配状态时返回404 notFound(); } }; export default StatePage;
方案二:结合Middleware与自定义错误页面
如果需要批量匹配路由,可通过Middleware拦截请求,直接返回503响应和自定义页面,避免重定向丢失状态码。
步骤1:创建自定义503组件
在项目中新建可复用的503组件(比如components/Custom503.js):
export default function Custom503() { return ( <div className="flex flex-col items-center justify-center h-screen"> <h1>503 服务暂时不可用</h1> <p>我们正在进行系统维护,预计XX时间恢复访问</p> </div> ); }
步骤2:修改Middleware逻辑
import { NextResponse } from 'next/server'; import ReactDOMServer from 'react-dom/server'; import Custom503 from './components/Custom503'; export function middleware(request) { // 渲染自定义503组件为HTML const componentHtml = ReactDOMServer.renderToString(<Custom503 />); const fullHtml = ` <!DOCTYPE html> <html> <head> <title>503 服务不可用</title> <link rel="stylesheet" href="/styles/global.css"> </head> <body>${componentHtml}</body> </html> `; return new NextResponse(fullHtml, { status: 503, headers: { 'Content-Type': 'text/html; charset=utf-8', }, }); } export const config = { matcher: '/fa/programs/:country/:path*', // 修正匹配规则,覆盖所有子路由 };
关键注意事项
- 不要直接
throw new Error(503):这会触发Next.js默认500错误页,状态码为500而非503。 - 路由匹配规则:Middleware的
matcher需用:path*匹配所有子路由,避免遗漏。 - 样式引入:确保HTML字符串中正确引入全局样式或Tailwind配置,避免错误页样式丢失。
内容的提问来源于stack exchange,提问作者negin shafaei
相关产品推荐
相关产品推荐

