在 NextJS 13 中从服务器端重定向

问题描述 投票:0回答:0

我目前正在开发 nextjs 13 应用程序,我在其中使用服务器端的 firebase 对用户进行身份验证。身份验证正在运行,但是如果登录页面未进行身份验证,我将尝试设置重定向。我正在尝试在布局上执行此操作,但是我无法使重定向真正起作用。布局应该在服务器端运行,所以我不确定我错过了什么。

import '../styles/theme.scss';
import Header from '@/components/header/header';
import verifyCookie from '@/firebase/auth/verify';
import {redirect} from 'next/navigation';

export const metadata = {
  title: 'My website',
  description: 'This is a test website',
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
    const isValid = await verifyCookie('user');
    console.log(isValid);

    // code is going into here, but the redirect is not doing anything...
    if (!isValid) { 
      try {
        redirect("/login"); 
      }
      catch (e) {
        console.log("redirecting to /login");
      }
    }

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </head>
      <body>
        
          <Header />
          {children}
   
      </body>
    </html>
  );
}
next.js http-redirect nextjs13
© www.soinside.com 2019 - 2024. All rights reserved.