Next.js Discord

Discord Forum

Can't access the set cookie after login in the middleware.

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
When the user logs in, I request the local API and set the cookie. Then I want to redirect the user to the dashboard subpage but it does not as it identifies the user as not logged in but the cookie is set. I'm not able to access the cookie in the middleware.

export async function login(name: string, email: string, remember: boolean) {
    const user = { name, email, remember };

    const expires = getExpirationTime(user.remember);
    const session = await encrypt({ user, expires });

    cookies().set(process.env.COOKIE_NAME, session, { expires, httpOnly: true, path: "/", sameSite: "lax" });
}


async function onSubmit(values: zod.infer<typeof formSchema>) {
    await fetch("/api/auth/login", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ ...values, remember })
    }).then((res) => res.json());
    const redirectURL = searchParams && searchParams.redirectURL;
    if (redirectURL) router.push(redirectURL);
}


export async function middleware(req: NextRequest) {
    const pathname = req.nextUrl.pathname;
    const session = await getSession();

    if (session) await updateSession(req);

    if (!session && protectedRoutes.includes(pathname) && pathname !== "/login") {
        const redirectURL = new URL("/login", req.nextUrl.origin);

        redirectURL.searchParams.append("redirectURL", req.nextUrl.pathname);

        return NextResponse.redirect(redirectURL, { status: 307 });
    }

    console.log("SESSION", session);
}

0 Replies