skip to Main Content

I got a login page, that I need to redirect after login success to app section and app section that redirects to login if no user is logged.

The redirect in AuthGuard component works great:

import { PropsWithChildren, ReactNode } from "react";
import appState from "./zustand";
import { redirect } from "next/navigation";

const AuthGuard = ({ children }: PropsWithChildren): ReactNode => {
    const user = appState((state) => state.User);
    if (!user) {
        // if user is not logged in, redirect to login page
        redirect("/user/login");
    }
    return children;
}

export default AuthGuard;

but I can’t get rid of error Uncaught (in promise) Error: NEXT_REDIRECT in FormLogin component:

"use client"

import { login } from "@/utils/api/actions/user";
import appState from "@/utils/state/zustand";
import { redirect } from "next/navigation";
import { FormEventHandler } from "react";

const FormLogin = (): JSX.Element => {
    const handleLogin: FormEventHandler = async (e) => {
        // stop form from submitting
        e.preventDefault();

        // login logic...
        
        // login against backend
        const user = await login(...)

        if (user) {
            // set user in state
            appState.setState({ User: user });

            redirect("/app/")
        } else {
            // show error etc.
        }
    }

    return <form onSubmit={handleLogin}>
        //...
    </form>
}

export default FormLogin;

I searched internet, there are some issues with Next 13.x, but it tells that the redirect gives error, but redirects, so advice is to ignore the error.
In my case it doesn’t do anything… It stays with current page.

Next.js v14.0.3

Any idea? Thanks

2

Answers


  1. Chosen as BEST ANSWER

    Resolved by putting redirect into useEffect box listening to user state changes:

        useEffect(()=>{
            if (user !== null){
                redirect("/app")
            }
        }, [user])
    

  2. I think nextjs calls redirect two times. Once in FormLogin second time in redirect("/user/login"); Which causes it to freak out.

    Try removing one redirect to fix error.

    After that I suggest to keep all redirection logic inside auth-guard. And updating it’s logic to make sure that it will be one redirect at a time.

    if (!user) {
            // if user is not logged in, redirect to login page
            redirect("/user/login");
        } else if(user && justLoggedIn) {
           // If user just logged in redirect to app.
           redirect("/app");
        }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search