Using the cookies-next package,
according to their docs, accessing cookies client side is as simple as getCookie('key'); - client side
I have a simple function in my Next JS app,
const handleAddToCart = () => {
const token = getCookie('cookie-token')
console.log('token', token)
}
I see nothing is returned in the log. Although I do see the cookie does exist when checking my developer tools. What am I doing wrong here?
You can use next-client-cookies
for Next.js 13 (app directory):
'use client';
import { useCookies } from 'next-client-cookies';
const MyComponent = () => {
const cookies = useCookies();
return (
<div>
<p>My cookie value: {cookies.get('my-cookie')}</p>
<button onClick={() => cookies.set('my-cookie', 'my-value')}>
Set cookie
</button>
{' | '}
<button onClick={() => cookies.delete('my-cookie')}>Delete cookie</button>
</div>
);
};
This is currently the only solution for SSR cookies with Next v13.
Disclaimer: I'm the author of this package.
Yea I think john had the best answer - I just made this util function
export const getClientSideCookie = (name: string): string | undefined => {
const cookieValue = document.cookie
.split('; ')
.find((row) => row.startsWith(`${name}=`))
?.split('=')[1];
return cookieValue;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With