-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
When a cookie is created:
The browser stores the cookie locally
The cookie is sent to the server with every request
The server can read and respond based on cookie data
JavaScript can only access cookies that are not marked as HttpOnly.
To create a cookie, assign a value to document.cookie.
document.cookie = "username=Rohit";
This creates a cookie that expires when the browser is closed.
let expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 7);
document.cookie = "user=Ananya; expires=" + expiryDate.toUTCString();
This cookie will expire after 7 days.
document.cookie = "theme=dark; path=/";
This cookie is accessible across the entire website.
The document.cookie property returns all cookies as a single string.
console.log(document.cookie);
Output example:
username=Rohit; theme=dark
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.
To update a cookie, simply set it again with the same name.
document.cookie = "username=Vikas; path=/";
The old value is overwritten.
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.
Cookies support several attributes that control their behavior.
Defines when the cookie will be deleted.
expires=Wed, 31 Dec 2025 12:00:00 UTC
Defines where the cookie is accessible.
path=/
Ensures the cookie is sent only over HTTPS.
secure
Controls cross-site cookie behavior.
SameSite=Strict
SameSite=Lax
SameSite=None
This attribute is important for security and preventing CSRF attacks.
function saveName(name) {
document.cookie = "username=" + name + "; path=/";
}
saveName("Neha");
let user = getCookie("username");
if (user) {
console.log("Welcome back " + user);
}
document.cookie = "theme=light; path=/";
This is often used for dark or light mode preferences.
document.cookie = "sessionId=abc123; path=/";
Servers commonly use this approach for authentication.
function logout() {
document.cookie = "sessionId=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
}
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.
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.
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.
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.
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.
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.
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.
How can you create a cookie named username with the value Vicky that lasts for 7 days?
Write a function to read a cookie by its name and return its value.
How can you update an existing cookie username to a new value VickyUpdated?
Write code to delete a cookie named username.
How can you check if a cookie exists and display an alert if it does?
Create a form where the user enters their email, save it in a cookie, and display it later.
How can you set a cookie that is accessible throughout the entire website?
Write a program to save a user’s preferred language in a cookie and greet them in that language.
How can you create a cookie that expires at the end of the session (when the browser closes)?
Create a personalized welcome message using a cookie that remembers the user’s name.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
