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
In latest versions (AuthJS/NextAuth 5 + Prisma 5.14, NextJS 15):
Using SessionContext works for me:
/**
* Session provider wrapper
* @param children - The children to render
*
* @returns The session provider wrapped component tree
*/
async function AppSessionProvider({ children }: PropsWithChildren): Promise<React.ReactNode> {
// require user to be logged in
const session = await auth();
if (!session) {
// user is not logged in
redirect("/auth/login");
}
return (
<SessionProvider session={session}>
{children}
</SessionProvider>
)
}