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

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>
);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With