Currently, I'm attempting to validate whether a user is logged in and if not, redirect them to the login page.
Here's the code snippet I am using:
import { onAuthStateChanged } from 'firebase/auth'
import { auth } from '../src/firebaseConfig'
import { redirect } from 'next/navigation'
// ...
export default async function Home() {
onAuthStateChanged(auth, (user) => {
if (!user) {
redirect('/login')
}
})
// ...
However, I encounter an error with this code:
error - node_modules/next/dist/client/components/redirect.js (47:18) @ getRedirectError
error - unhandledRejection: Error: NEXT_REDIRECT
at getRedirectError (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:40:19)
at redirect (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:46:11)
at eval (webpack-internal:///(sc_server)/./app/layout.tsx:29:70)
at eval (webpack-internal:///(sc_server)/./node_modules/@firebase/auth/dist/node-esm/totp-e47c784e.js:2684:26) {
digest: 'NEXT_REDIRECT;replace;/login'
}
In another branch where I haven't yet implemented authentication checking, I have similar code in the same location which works perfectly fine.
import { redirect } from "next/navigation";
export default function Home() {
redirect("/home");
}
What am I missing or doing incorrectly in my initial code?