Reading Cookie in JavaScript

JavaScript allows developers to read cookies using the document.cookie property, which stores all cookies as a string. To extract specific values, developers often create functions that parse this string. Security considerations, like proper decoding and HttpOnly attributes, are crucial.

Example: To demonstrate reading an already created cookie in JavaScript.

Javascript




function getCookie(cookieName) {
    const cookies = document.cookie.split('; ');
    for (const cookie of cookies) {
        const [name, value] = cookie.split('=');
        if (name === cookieName) {
            return decodeURIComponent(value);
        }
    }
    return null;
}
const courseName = getCookie('courseName');
console.log('Course Name:', courseName);


Output:

Course Name: webDeveopment bootcamp

JavaScript Cookies

JavaScript cookies are small data stored on a user’s device by a web browser. These cookies play a crucial role in web development, enabling websites to store and retrieve information about user preferences, session states, and other data. Cookies facilitate a more personalized browsing experience by allowing websites to remember user actions and preferences. They are widely used for user authentication, tracking, and maintaining session states.

Table of Content

  • Creating Cookie in JavaScript
  • Reading Cookie in JavaScript
  • Changing Cookie in JavaScript
  • Deleting Cookie in JavaScript

Similar Reads

Creating Cookie in JavaScript

Cookies are created by a web server and sent to the user’s browser as part of the HTTP response headers....

Reading Cookie in JavaScript

...

Changing Cookie in JavaScript

JavaScript allows developers to read cookies using the document.cookie property, which stores all cookies as a string. To extract specific values, developers often create functions that parse this string. Security considerations, like proper decoding and HttpOnly attributes, are crucial....

Deleting Cookie in JavaScript

...