How To Get Cookies In Javascript Using A Custom Hook
  • Work
    ,
  • About
    ,
  • Blog
    ,
  • Contact
Get In Touch
  • Home
  • Work
  • About
  • Blog
  • Contact

Developer & Designer

OreoGrapher © 2024
Published on: Mon Nov 25 2024
By - OreoGrapher
hook

How to Get Cookies in JavaScript Using a Custom Hook

How to Get Cookies in JavaScript Using a Custom Hook Image

Why Use a Custom Hook for Cookies?

While JavaScript's document.cookie provides access to cookies, it returns all cookies as a single string. Parsing this string repeatedly across your codebase can lead to duplicated logic and errors. A custom hook like getCookie simplifies cookie retrieval, ensuring consistent behavior.

The getCookie Implementation

Here's the implementation of the getCookie function:

javascriptCopy code

const getCookie = (name) => {
  const cookies = document.cookie
    .split(";")
    .map((cookie) => cookie.trim())
    .filter((cookie) => cookie.startsWith(`${name}=`));

  if (cookies.length === 0) {
    return null;
  }

  return decodeURIComponent(cookies[0].split("=")[1]);
};

export default getCookie;

Example Usage

Imagine you have a cookie named authToken and want to retrieve its value:

import getCookie from "./getCookie";

const token = getCookie("authToken");
if (token) {
  console.log("Auth Token:", token);
} else {
  console.log("Auth Token not found");
}

Handling Edge Cases

  • Cookie Not Found: The function returns null if the specified cookie does not exist.
  • Multiple Cookies with the Same Name: Only the first matching cookie is returned. Ensure cookie names are unique in your application.

Leave a Comment

No comments yet

Similar Blogs

(0)