I have a client component that checks the authentication state and is incorporated into app/layout.tsx
. The objective is to determine if the user is logged in or not. If not, the user is redirected to the login page if the current URL path is not /login
. If the user is logged in, they are redirected to /
if the current URL path is /login
. Here’s the code:
(Firebase)
onAuthStateChanged(auth, (user) => {
if (user) { // if user is logged in
if (path === "/login") {
router.push("/");
}
} else { // if user is not logged in
if (path !== "/login") {
router.push("/login");
}
}
});
Notice that using this code, the user cannot access any 404 pages if they aren’t logged in. The code will redirect the user to the login page if they do so, which I don’t want. To prevent this, I need to detect if it’s a 404 page.
So, how do I check if it’s a 404 page with Next.js 13?
Let me know if you need any additional info to solve the issue.
2
Answers
Next.js and Error Handling
In
Next.js
the built-in Error page component,_error.js
or_error.tsx
located in the /pages directory, handles all error codes, including 404. However, it doesn’t directly provide a mechanism for checking if the current page is a 404 from another component.A possible solution to your problem is to set a state within your root component
layout.tsx
that’s altered whenever the Error page component is triggered. You can achieve this viaReact
context or a state management library of your choice.So lets go on with my approach:
First we need to construct a context. I have created a
NotFoundContext
for this case.The Code:
Now we need to wrap the application with
NotFoundProvider
that we have defined.The Code:
We need to adjust
_error.js
or_error.tsx
to reflect theisNotFound
status. Just setisNotFound
to true inside thejs
ortsx
file.The Code:
Now with everything at its place
isNotFound
can be accessed and utilized within your own component.The Code:
I hope this helps you!
Usually, redirection or authentication is handled in middleware files or a wrapper files. if you still want to follow your approach, you should manually defined all the routes in your app