#Cookies

1 messages · Page 1 of 1 (latest)

grand venture
#

how to read cookies in client side?

vivid ridgeBOT
#

Hi @grand venture. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To read cookies on the client side in a Next.js application, you can use the standard JavaScript document.cookie API. Here is a function that demonstrates how to read a specific cookie by name:

export function getCookie(name: string) {
  if (typeof document === "undefined") return;

  const value = "; " + document.cookie;
  const decodedValue = decodeURIComponent(value);
  const parts = decodedValue.split("; " + name + "=");

  if (parts.length === 2) {
    return parts.pop()?.split(";").shift();
  }
}

This function checks if the document object is available (which ensures the code is running on the client side), then reads and decodes the cookies, and finally extracts the value of the specified cookie.

For more information on handling cookies in Next.js, you can refer to the Next.js documentation (https://nextjs.org/docs).

If you need to read cookies on the server side or in other contexts, please let me know!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: