In my case, I was using Next.js v14 app directory and in client components the document.cookie
always returned an empty value. Also tried 3rd party libraries, such as next-client-cookies
and js-cookie
, but the result kept the same.
Tried to use React Context API as follows and it worked.
"use client"
import { createContext, PropsWithChildren, useContext, useMemo } from 'react';
interface CookieContextType {
cookie: string
}
export const CookieContext = createContext<CookieContextType | null>(null);
export const useCookies = (): CookieContextType => {
const context = useContext(CookieContext);
if (!context) {
throw new Error('useCookies must be used within a CookieProvider');
}
return context;
};
export const CookieProvider = ({ children, cookie }: PropsWithChildren<{
cookie: string | undefined,
}>) => {
const providerValue = useMemo(() => ({
cookie: cookie,
}), [cookie]);
return (
<CookieContext.Provider value={providerValue as CookieContextType}>
{children}
</CookieContext.Provider>
);
};
In app/layout.tsx
, wrap the provider:
...
<CookieProvider cookie={getCookie()}>
{children}
</CookieProvider>
...
where getCookie()
is a Server Action:
"use server";
import { cookies } from "next/headers";
const getCookie = () => {
return cookies().get('your-cookie-name')?.value
}
export default getCookie
Now in a client component, one can use const { cookie } = useCookies()
to get the cookie value.
Hope it helps someone.