Accessing Cookie client-side with Next JS
Asked Answered
C

8

12

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?

Constringe answered 24/1, 2023 at 17:39 Comment(0)
N
29

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.

Nimesh answered 3/8, 2023 at 12:10 Comment(4)
Thank you ! both for that answer and for your package πŸš€ – Verbal
I get this error using this package: github.com/moshest/next-client-cookies/issues/3 – Asthenopia
Hi Lonel, I don't think this issue related to the package. Please see more details on the issue. – Nimesh
Awesome package! – Lanate
B
2

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;
        };
Bloc answered 6/1 at 3:48 Comment(0)
M
1

You have the set the cookie in api file before sending the response to the cookie. you set the token when user logins, so maybe in pages/api/auth.signin endpoint

import { setCookie } from "cookies-next";

const token=setTokenHere // what ever library you are using
// we tell client that, I want you to store this piece of information as a cookie
setCookie("jwt", token, { req, res, maxAge: 60 * 6 * 24 });
// then send the response object
return res.status(200).json({resObject
    });

on the client, whenever you need to access this cookie

 import { getCookie } from "cookies-next";
 // "jwt" is key, 
 const jwtToken = getCookie("jwt");
Myna answered 21/2, 2023 at 19:3 Comment(0)
C
1

In Next.js version 13, you could set/get the cookie in api functions with cookies-next. Cookie is generated when user logins.

Install

pnpm i cookies-next

Set Cookie

import { setCookie } from "cookies-next";

setCookie("cookieKey", value, { req, res, maxAge: 60 * 6 * 24 }); // then you can access the cookie in client-side

Get Cookie

  import { getCookie } from "cookies-next";

  const cookie = getCookie("cookieKey");
Countertype answered 4/9, 2023 at 19:38 Comment(0)
H
1

I use the

document.cookie

within useEffect, but still I'm not really sure if this is right to use in this case, since using document object is not recommended to use in React js. I'm just sharing my idea if this is ok to deal with. Document: cookie property

Hiers answered 1/11, 2023 at 2:28 Comment(0)
G
1

You can acces directly with document.cookie, and you will receive as a response a string with all cookies. For example:

const myCookies = document.cookie 
console.log(myCookies)

More details in this article.

Gowrie answered 13/2 at 0:0 Comment(0)
U
0

if you know that cookies have value, just refresh the page, and you can see them! but your cookies were of no value so first, check "setCookie"!

if you want to load in other components! you have to use "useEffect".

const token = getCookie('cookie-token')
const [myToken , setMyToken] = useState("")

useEffect(() => {
  console.log(token)
  setMyToken(token)
},[token])
console.log(myToken)

if you have SSR components:

export const getServerSideProps = ({ req, res }) => {
  const token = getCookie('cookie-token', { req, res });
  ...
}
Unbroken answered 24/1, 2023 at 22:56 Comment(0)
T
0

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.

They answered 12/8 at 17:54 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.