You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:52:06