在Next.js App目录中实现服务端页面重定向
在Next.js服务端渲染页面中实现服务端重定向
在Next.js的App Router(React Server Components)体系下,服务端页面组件要实现服务端重定向,不能直接返回NextResponse.redirect,而是要使用Next.js官方提供的**redirect函数**(从next/navigation导入)。
修改后的完整代码示例
import { redirect } from 'next/navigation'; // 导入你的其他依赖:getGameInfo、getUserContextFromToken、isEmpty等 // 服务端渲染页面组件 export default async function Packs() { const cookiesStore = cookies() const token = cookiesStore.get('token')?.value const gameInfo = await getGameInfo() const user = await getUserContextFromToken(token || "") as UserContext const theme = getThemeForLevel(user?.level || 1) if (isEmpty(user)) { // 触发服务端重定向,默认使用302临时重定向 redirect(AppRoutes.home); } return ( <PacksPage theme={theme} currentLevel={user.level} packSize={gameInfo.packSize} totalLevels={gameInfo.totalLevels} /> ); }
核心要点说明
redirect函数是App Router专为服务端组件设计的重定向方案,调用后会立即终止当前页面的渲染流程,直接发起服务端层面的重定向。- 如果需要使用301永久重定向,可在第二个参数中指定状态码:
redirect(AppRoutes.home, { status: 301 })。 - 注意:该函数仅能在服务端组件或服务端路由处理器中调用,无法在客户端组件内使用。
内容的提问来源于stack exchange,提问作者karthik suryadevara
相关产品推荐
相关产品推荐

