Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from server side in NextJS 13

I am currently working on a nextjs 13 app where I am authenticating the user using firebase from the server side. The authentication is working, however I am trying to set up a redirect if no authentication has taken place to the login page. I am trying to do this on the layout, however I am unable to get the redirect to actually work. The layout should be running server side so I am not sure what I am missing.

The documentation I am following doesn't seem to clarify much either https://beta.nextjs.org/docs/api-reference/redirect

Error shown in browser

    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>
      );
    }
like image 493
Matthew Pigram Avatar asked Nov 17 '25 11:11

Matthew Pigram


1 Answers

From NextJS 14 onward, if you want to redirect user from server side component, you can use redirect().

import it from 'next/navigation' package

import { redirect } from "next/navigation"

and pass the url parameter to it

redirect(url);

To redirect from client side component, one can always use useRouter(). It can be imported from 'next/navigation' package.

import { useRouter} from "next/navigation"

const router = useRouter();

you can use router.push(url) to redirect user to desired path.

like image 61
iAmSauravSharan Avatar answered Nov 20 '25 19:11

iAmSauravSharan