JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Cookies


JavaScript cookies are a simple way to store small pieces of data in the user’s browser. They are commonly used to remember user preferences, manage sessions, track login status, and personalize user experience. Even though modern storage options like Local Storage and Session Storage exist, cookies are still widely used, especially for authentication and server-side communication.

In this tutorial, you will learn what JavaScript cookies are, how they work, how to create, read, update, and delete cookies, along with practical examples, common mistakes, best practices, and real-world use cases.

What Are Cookies in JavaScript

A cookie is a small text file stored in the browser and sent to the server with every HTTP request. Cookies usually store data in the form of key-value pairs.

Cookies are accessible in JavaScript using:

document.cookie

Each cookie can store a limited amount of data, typically up to 4KB, and can have additional attributes like expiration date, path, and security settings.

Why Cookies Are Important

Cookies are important because they allow you to:

  • Maintain user login sessions

  • Store user preferences like theme or language

  • Track user activity

  • Share data between client and server

  • Implement authentication systems

  • Improve user experience

Without cookies, websites would not be able to remember users across different pages or visits.

How Cookies Work

When a cookie is created:

  1. The browser stores the cookie locally

  2. The cookie is sent to the server with every request

  3. The server can read and respond based on cookie data

JavaScript can only access cookies that are not marked as HttpOnly.

Creating Cookies in JavaScript

To create a cookie, assign a value to document.cookie.

Basic Cookie Creation

document.cookie = "username=Rohit";

This creates a cookie that expires when the browser is closed.

Cookie with Expiration Date

let expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 7);

document.cookie = "user=Ananya; expires=" + expiryDate.toUTCString();

This cookie will expire after 7 days.

Cookie with Path

document.cookie = "theme=dark; path=/";

This cookie is accessible across the entire website.

Reading Cookies in JavaScript

The document.cookie property returns all cookies as a single string.

console.log(document.cookie);

Output example:

username=Rohit; theme=dark

Reading a Specific Cookie

function getCookie(name) {
    let cookies = document.cookie.split("; ");
    for (let cookie of cookies) {
        let parts = cookie.split("=");
        if (parts[0] === name) {
            return parts[1];
        }
    }
    return null;
}

console.log(getCookie("username"));

This function safely extracts a specific cookie value.

Updating Cookies

To update a cookie, simply set it again with the same name.

document.cookie = "username=Vikas; path=/";

The old value is overwritten.

Deleting Cookies

To delete a cookie, set its expiration date to a past date.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

The browser removes the cookie immediately.

Cookie Attributes Explained

Cookies support several attributes that control their behavior.

expires

Defines when the cookie will be deleted.

expires=Wed, 31 Dec 2025 12:00:00 UTC

path

Defines where the cookie is accessible.

path=/

secure

Ensures the cookie is sent only over HTTPS.

secure

SameSite

Controls cross-site cookie behavior.

SameSite=Strict
SameSite=Lax
SameSite=None

This attribute is important for security and preventing CSRF attacks.

Practical Examples

Example 1: Remember User Name

function saveName(name) {
    document.cookie = "username=" + name + "; path=/";
}

saveName("Neha");

Example 2: Display Welcome Message

let user = getCookie("username");

if (user) {
    console.log("Welcome back " + user);
}

Example 3: Theme Preference

document.cookie = "theme=light; path=/";

This is often used for dark or light mode preferences.

Example 4: Session Tracking

document.cookie = "sessionId=abc123; path=/";

Servers commonly use this approach for authentication.

Example 5: Logout Functionality

function logout() {
    document.cookie = "sessionId=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
}

Cookie Size and Limitations

Cookies have limitations:

  • Maximum size is around 4KB

  • Limited number per domain

  • Sent with every HTTP request

  • Can affect performance if overused

For storing large data, Local Storage or IndexedDB is more suitable.

Common Mistakes

  • Storing sensitive data in plain text

  • Forgetting to set expiration

  • Not setting proper path

  • Overusing cookies for large data

  • Ignoring security attributes

These mistakes can cause security risks and performance issues.

Best Practices

  • Store minimal data in cookies

  • Use cookies mainly for authentication and preferences

  • Set proper expiration dates

  • Always use secure and SameSite attributes when possible

  • Avoid storing passwords or sensitive information

Following best practices ensures safer and more reliable applications.

Cookies vs Local Storage

Understanding the difference helps choose the right option.

  • Cookies are sent to the server automatically

  • Local Storage is client-side only

  • Cookies have size limitations

  • Local Storage supports larger data

Cookies are best for server communication, while Local Storage is better for client-only data.

Real-World Applications

JavaScript cookies are used in:

  • Login and authentication systems

  • Remember me functionality

  • Language and region selection

  • Shopping cart sessions

  • Analytics and tracking

  • User preference storage

Despite newer technologies, cookies remain a core web concept.

Security Considerations

When working with cookies:

  • Never store passwords

  • Use HTTPS with secure cookies

  • Validate cookie data on the server

  • Protect against CSRF using SameSite

Security is critical when handling user data.

Summary of JavaScript Cookies

JavaScript cookies provide a simple and effective way to store small pieces of data in the browser and communicate with the server. By learning how to create, read, update, and delete cookies, developers can manage sessions, personalize user experience, and build reliable web applications. When used carefully with proper security practices, cookies remain an essential tool in modern web development.


Practice Questions

  1. How can you create a cookie named username with the value Vicky that lasts for 7 days?

  2. Write a function to read a cookie by its name and return its value.

  3. How can you update an existing cookie username to a new value VickyUpdated?

  4. Write code to delete a cookie named username.

  5. How can you check if a cookie exists and display an alert if it does?

  6. Create a form where the user enters their email, save it in a cookie, and display it later.

  7. How can you set a cookie that is accessible throughout the entire website?

  8. Write a program to save a user’s preferred language in a cookie and greet them in that language.

  9. How can you create a cookie that expires at the end of the session (when the browser closes)?

  10. Create a personalized welcome message using a cookie that remembers the user’s name.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top