In Next.js 14 I’m trying to have one function that can get a cookie value for both client and SSR components, but it’s failing to do that in client components. How can I have it do that for any component regardless of where it’s rendered?
I’ve been making effort with this, but the client component has a problem with it:
import { RequestCookie } from 'next/dist/compiled/@edge-runtime/cookies';
import { cookies } from 'next/headers';
import Cookies from 'js-cookie';
export const getCookie = (cookie: string): string | undefined => {
if (typeof window === 'undefined') {
const returnedCookie: RequestCookie | undefined = cookies().get(cookie);
return returnedCookie && returnedCookie.value;
} else {
const returnedCookie: string | undefined = Cookies.get(cookie);
return returnedCookie;
}
};