Search code examples
next.jsserver-side-rendering

Redirect to another page server-side in the app directory of Next.js


I have a server-rendered page in a Next.js application and I want to check a condition and redirect to another page. See the code below to understand better:

// This is a server-rendered page
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)) {
    // Instead of sending the home page we should be able to redirect
    return <HomePage sessionExpired={true} user={null} theme={theme} totalLevels={gameInfo.totalLevels} />
    // return NextResponse.redirect(AppRoutes.home, 302); // (is something like this possible)
  }
  return (
    <PacksPage theme={theme} currentLevel={user.level} packSize={gameInfo.packSize} totalLevels={gameInfo.totalLevels} />
  );
}

Solution

  • You can use the redirect function from next/navigation, as an example like so:

    // app/page.js
    
    import { redirect } from 'next/navigation'
    
    export default async function Page() {
      const res = await fetch('https://...')
      if (!res.ok) {
        redirect('/login')
      }
     
      // ...
    }