For your information, I am a new noob to programming.
Background:I am creating authentication for my app. I am using NextJS 14 with AppRouter and laravel on the backend to manage tokens. I have created a function in nextJS where it simply checks whether the user is authenticated or not by simply sending a request using fetchAPI to the laravel endpoint and if the response is not OK (i.e 401 (Unauthorized)) then the user should be redirected to homepage (i.e "/").
The Error:When I try to use NextJS function "redirect()". It throws an error:Error: NEXT_REDIRECT
My Code:
import { redirect } from "next/navigation";import { hasCookie } from "cookies-next";import { cookies } from "next/headers";import { BASE_URL, API_ENDPOINTS } from "@/app/data/api";export default function useAuth() { const existingToken = hasCookie("token", { cookies }); // returns 'true' if the token exists console.log("existing token?", existingToken); const cookiesSet = cookies(); const checkUser = async () => { if (existingToken) { const token = cookiesSet.get("token").value; // returns the token from cookies console.log("the token: ", token); try { const response = await fetch( `${BASE_URL}${API_ENDPOINTS.PROFILE_DETAILS}`, { headers: { Authorization: `Bearer ${token}`,"Content-Type": "application/json", }, } ); if (!response.ok) { console.log("User is not authenticated, response not ok"); redirect("/"); // The issue is here. It does not redirect } } catch (error) { console.error("Error:", error.message); } } }; checkUser(); return null; // Return null to avoid rendering any content}
My "dashboard/page.jsx" (where I am calling the function)
import useAuth from '../Auth/hooks/useAuth';export default function Dashboard() { useAuth(); return (<> dashobard</> )}
Note:I want this redirect functionality on the server side.
What I am trying to Achieve:I want to create a general function for server side redirection. Whenever I call it in any of my page.jsx. It should check if the user is not authorized then it should be redirected to homepage.
What I triedI tried to get things done using "useRouter" but later discovered it only works on client-side. I am wandering for 2 days to get the solution. Even ChatGPT was unable to help me.