JavaScript Cookies – How To Create Cookies in JavaScript

JavaScript Cookies - How To Create Cookies in JavaScript

JavaScript Cookies – How To Create Cookies in JavsScript . A cookie is a small piece of data stored by a web browser that helps maintain information between a server-side application and a client-side user. This information persists even after the user navigates away from the website and can be used to remember user preferences and maintain session state.

JavaScript Cookies – Cookies are usually formatted as strings in the form of name-value pairs, separated by semicolons. For example, a cookie might look like this: user=JohnDoe; sessionID=12345. This format allows cookies to store a variety of user-related information, which can be accessed across multiple web pages.

JavaScript Cookies – How Cookies Work ?

When a user sends a request to a server, each request is typically treated as a new request by a different user. This is because HTTP, the protocol used for web communication, is stateless by nature. To overcome this limitation and recognize returning users, cookies are used.

  1. Setting Cookies: When the server responds to a user’s request, it includes a cookie in the HTTP response headers. This cookie is then

JavaScript Cookies – Example Response Header:

Set-Cookie: user=JohnDoe; sessionID=12345; expires=Wed, 09 Jun 2021 10:18:14 GMT; path=/

Storing Cookies: The browser stores the cookie and associates it with the domain and path specified in the cookie’s attributes. This way, the cookie will be sent only to the intended server and for the specified path.

Sending Cookies: On subsequent requests to the same server, the browser automatically includes the stored cookies in the HTTP request headers. This allows the server to recognize returning users and maintain their session state.

Example request header:

Cookie: user=JohnDoe; sessionID=12345

JavaScript Cookies- Example Scenario

Consider a user visiting an e-commerce website. The first time they log in, the server might set a cookie with their username and a unique session ID. This information helps the server remember the user and keep them logged in as they navigate through different pages of the website.

Benefits of Using Cookies

  • Session Management: Cookies enable servers to maintain user sessions, allowing users to stay logged in and continue their activities without re-authenticating on every page.
  • Personalization: Websites can use cookies to store user preferences and personalize their experience, such as language settings or theme choices.
  • Tracking and Analytics: Cookies help track user behavior across a website, providing valuable data for website analytics and marketing purposes.

Cookies are a fundamental part of web browsing, making it possible to create rich, interactive, and personalized web experiences by maintaining continuity between the client and server.

How to create a Cookie in JavaScript?
we can create, read, update, and delete a cookie by using document.cookie property in javascript.

The following syntax is used to create a cookie:

document.cookie="name=value";

Let us take an example:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Sona M";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

Example 2

Here, we display the cookie’s name-value pair separately.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie="username=Sona M";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

Next let us provide choices of color and pass the selected color value to the cookie. Now, cookie stores the last choice of a user in a browser.

So, on reloading the web page, the user’s last choice will be shown on the screen.

JavaScript Cookies Attributes

Cookies in JavaScript can be set with various attributes to control their behavior. These attributes define aspects like the cookie’s expiration, scope, and security. Here are the common attributes for cookies in JavaScript:

  1. Name and Value: The name-value pair that stores the actual data.
  2. Expires: Sets the expiration date for the cookie.
  3. Max-Age: Specifies the maximum age of the cookie in seconds.
  4. Domain: Defines the domain within which the cookie is accessible.
  5. Path: Limits the cookie to a specific path on the domain.
  6. Secure: Ensures the cookie is only sent over HTTPS connections.
  7. HttpOnly: Makes the cookie inaccessible to JavaScript, enhancing security.
  8. SameSite: Restricts how cookies are sent with cross-site requests.

Setting and Reading Cookies in JavaScript

To work with cookies in JavaScript, you typically use document.cookie. Here are examples demonstrating how to set, read, and delete cookies with different attributes.

Setting Cookies

You can set a cookie by assigning a string to document.cookie. Here’s an example of setting a cookie with different attributes:

// Setting a cookie with name-value pair
document.cookie = "username=JohnDoe";
// Setting a cookie with an expiration date
document.cookie = "username=JohnDoe; expires=Wed, 09 Jun 2021 10:18:14 GMT";
// Setting a cookie with max-age (expires in 1 hour)
document.cookie = "username=JohnDoe; max-age=3600";
// Setting a cookie for a specific domain
document.cookie = "username=JohnDoe; domain=example.com";
// Setting a cookie for a specific path
document.cookie = "username=JohnDoe; path=/account";
// Setting a secure cookie
document.cookie = "username=JohnDoe; secure";
// Setting an HttpOnly cookie
document.cookie = "username=JohnDoe; HttpOnly";
// Setting a cookie with SameSite attribute
document.cookie = "username=JohnDoe; SameSite=Strict";

Reading Cookies

Reading cookies involves accessing document.cookie, which returns a string containing all cookies for the current domain and path. You then need to parse this string to get individual cookies.

// Function to get a cookie by name
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
// Usage
let username = getCookie("username");
console.log(username); // Outputs: JohnDoe

Deleting Cookies

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

// Deleting a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
// Alternatively, you can use max-age
document.cookie = "username=; max-age=0";

Example: Managing User Preferences with Cookies

Let’s create an example where we manage user preferences (like theme color) using cookies.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Cookies</title>
</head>
<body>
<h1>Manage User Preferences</h1>
<label for="theme">Choose a theme:</label>
<select id="theme">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<button onclick="savePreference()">Save Preference</button>
<script>
// Function to save user preference in a cookie
function savePreference() {
const theme = document.getElementById('theme').value;
document.cookie = `theme=${theme}; max-age=31536000; path=/`; // Cookie valid for 1 year
alert('Preference saved!');
}
// Function to get a cookie by name
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
// Function to apply the saved theme preference
function applyPreference() {
const theme = getCookie('theme');
if (theme) {
document.getElementById('theme').value = theme;
document.body.className = theme;
}
}
// Apply the saved preference on page load
window.onload = applyPreference;
</script>
</body>
</html>

Conclusion

JavaScript cookies are essential tools for managing state and user preferences in web applications. They provide a mechanism to store information on the client-side, enabling seamless user experiences across multiple sessions and pages. By understanding and utilizing the various attributes associated with cookies, developers can exercise precise control over how cookies behave, enhancing both functionality and security.

In this guide, we’ve covered the basics of setting, reading, and deleting cookies in JavaScript. We’ve also delved into the attributes that can be used to customize cookie behavior:

  1. Name and Value: The fundamental data stored in cookies.
  2. Expires and Max-Age: Control the lifespan of cookies, ensuring they persist for as long as needed.
  3. Domain and Path: Specify the scope of cookies, determining where they are accessible.
  4. Secure: Ensures cookies are only sent over HTTPS, protecting sensitive data.
  5. HttpOnly: Prevents JavaScript access to cookies, mitigating XSS attacks.
  6. SameSite: Restricts how cookies are sent with cross-site requests, enhancing security against CSRF attacks.

By following best practices, such as setting appropriate expiration dates, using secure and HttpOnly flags, and managing the domain and path attributes wisely, developers can create robust and secure web applications. The provided examples demonstrate how to implement cookies in various scenarios, from simple data storage to complex user preference management.

In summary, mastering cookies in JavaScript allows developers to enhance the user experience, maintain stateful interactions, and build more secure applications. As you continue to develop your skills, keep experimenting with different attributes and scenarios to fully leverage the power of cookies in your web projects.

  1. stored by the user’s web browser.Example response header:

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>