Next.js Discord

Discord Forum

Setting cookies causes get cookies to rerender my component

Unanswered
Somali posted this in #help-forum
Open in Discord
SomaliOP
Title

11 Replies

SomaliOP
getCookies:
import { cookies } from "next/headers";

export function getCookies<ValueType>(
    key: string,
    defaultValue: ValueType
): ValueType {
    const cookieStore = cookies();
    const cookie = cookieStore.get(key)?.value;

    return cookie ? (JSON.parse(cookie) as ValueType) : defaultValue;
}
setCookies:
"use server";

import { cookies } from "next/headers";

export async function setCookie<ValueType>(key: string, value: ValueType) {
    cookies().set(key, JSON.stringify(value));
    console.log("cookie set", key, value);
}
Where I pass cookie to my context:
import { ThemeProvider } from "./theme.context";
import { getCookies } from "@/util/helpers/cookies/getCookies";
import type { ThemeStateProps } from "./theme.context";

export function ThemeProviderWithCookies({
    children
}: {
    children: React.ReactNode;
}) {
    const theme = getCookies<ThemeStateProps>("theme", "system");
    console.log("theme", theme);

    return <ThemeProvider cookie={theme}>{children}</ThemeProvider>;
}
Inside ThemeProvider I run setCookies
then it runs console.log("cookie set", key, value); from setCookies
right after though it runs console.log("theme", theme); from getCookies
I just can't seem to figure it out
For my usecase I just need to get cookies once when page loads in
I assume its because you cant just get the latest cookies without sending a new request because they are sent with the server response and not stored in the client side.
not while using custom route.ts with fetch
@Somali not while using custom route.ts with fetch
Does the fetch one auto-revalidate?
@Clown Does the fetch one auto-revalidate?
SomaliOP
The fetch has keepalive: true
which allows it to run even as we close the page