Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Cookie client-side with Next JS

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?

like image 448
Ben Shekhtman Avatar asked Sep 13 '25 13:09

Ben Shekhtman


2 Answers

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.

like image 89
Moshe Simantov Avatar answered Sep 16 '25 07:09

Moshe Simantov


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;
        };
like image 30
Nick Grato Avatar answered Sep 16 '25 09:09

Nick Grato