Nextjs 14 response cookies won't return to the client

74 views Asked by At

I am currently working on one of my project which is mainly focused on Nextjs api router (I've mainly used node with express in the past) I'm trying to auth a user using pocketbase as my custom database. I'm doing user auth using email and password and then storing the user data in a session as following:

import { encrypt } from "@/lib/actions";
import { db } from "@/pocketbase";
import { NextResponse, NextRequest } from "next/server";
import { serialize } from 'cookie'

export async function POST(request: NextRequest) {
    try {
        const values = await request.json();
        const { record } = await db.collection("users").authWithPassword(values.email, values.password);
        const expires = new Date(Date.now() + 30 * 1000 * 60 * 24);
        /* the encrypt function mainly just to sign a JWT contract */
        const session = await encrypt({ record, expires });
        const response = NextResponse.json({ session }, {
            status: 200, headers: {
                'Set-Cookie': serialize('session', session, { expires })
            }
        });
        return response;
    } catch (err: any) {
        return NextResponse.json({ message: err.message }, { status: 400 })
    }
}

My problem is that the cookie won't be sent back to the client at all and whenever I'm trying any diffrent approuch of sending the cookie it also won't work

Its been a few hours already and I'm frustrated by this

For more context: I'm trying to then access the session by this getSession helper function:

export async function getSession() {
    const session = cookies().get('session')?.value;
    if (!session) return null;
    return await decrypt(session);
}

And then I'm trying to access it in an AuthProtected Component:

import { getSession } from "@/lib/actions";
import { redirect } from "next/navigation";

export default async function AuthProtected({ children }: { children: React.ReactNode }) {
    const session = await getSession();
    console.log(session);
    return <>{children}</>
}

I'm getting null in the server console

I appriciate any solution or if I've made some kind of mistake I will be gald to take any sort of reviews for my code :)

Thanks

2

There are 2 answers

0
roee1454 On BEST ANSWER

Okay so I solved it and forgot to update Personally my problem was that I was sending the request via server action and not from the client itself

0
Yilmaz On

I think instead of NextResponse, use Response

From Here

Route Handlers in the Next.js App Router do not support using the NextResponse.next() method to forward to the next Middleware.

The Route Handler is considered the end of the middleware "chain". Handlers must always return a Response object instead.