Cookies in Next 14

I'm fairly new to SSR and server components. I am having trouble understanding cookies behavior with ssr and client in mind. My goal: Set cookie on NextJS backend, be able to see it in browser and in client components. My code:
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic"; // defaults to auto

export async function GET(request: Request, response: Response) {
const myCookies = cookies().getAll();
console.log(myCookies);

return NextResponse.json({ message: "API GET" });
}

export async function POST(request: Request) {
const cookieOptions = {
expires: new Date("2025-01-01"),
};
cookies().set("test", "test", cookieOptions);
const myCookies = cookies().getAll();
console.log(myCookies);

return NextResponse.json({ message: "API POST" });
}
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic"; // defaults to auto

export async function GET(request: Request, response: Response) {
const myCookies = cookies().getAll();
console.log(myCookies);

return NextResponse.json({ message: "API GET" });
}

export async function POST(request: Request) {
const cookieOptions = {
expires: new Date("2025-01-01"),
};
cookies().set("test", "test", cookieOptions);
const myCookies = cookies().getAll();
console.log(myCookies);

return NextResponse.json({ message: "API POST" });
}
This is my route.ts file.
import { cookies } from "next/headers";
import React from "react";

const AccountPage = async () => {
const test = await fetch("http://localhost:3003/api", {
method: "POST",
credentials: "include",
});

const res = await fetch("http://localhost:3003/api");
const data = await res.json();

const myCookies = cookies().getAll();
console.log(myCookies);

return (
<div>
AccountPage
<div>{JSON.stringify(data)}</div>
</div>
);
};

export default AccountPage;
import { cookies } from "next/headers";
import React from "react";

const AccountPage = async () => {
const test = await fetch("http://localhost:3003/api", {
method: "POST",
credentials: "include",
});

const res = await fetch("http://localhost:3003/api");
const data = await res.json();

const myCookies = cookies().getAll();
console.log(myCookies);

return (
<div>
AccountPage
<div>{JSON.stringify(data)}</div>
</div>
);
};

export default AccountPage;
This is my server component. I know I said my goal was to read my cookie in browser but as first step I wanted to read it in my server component. When I print myCookies on my POST route, I can see the cookie, but on the get request or on the component I get an empty array.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server