Store data in cookies using JavaScript
Cookies are small data files that are stored on a user’s device when they browse the internet. They are commonly used to store user preferences, login credentials, and other small pieces of information. In JavaScript, cookies can be created, read, and deleted using the document.cookie
object. In this article, we will explore how to store data in a cookie using JavaScript and provide multiple examples to illustrate the concept.
Creating a Cookie
Creating a cookie in JavaScript involves setting the document.cookie
property to a string that contains the data to be stored, along with any optional parameters. The basic syntax for creating a cookie is as follows:
1 | document.cookie = "key=value; expires=expiration_time; path=path_name"; |
Here, key
is the name of the cookie, and value
is the data to be stored. The expires
parameter sets the expiration date for the cookie. After this date, the cookie will no longer be stored on the user’s device. The path
parameter sets the path for which the cookie is valid. This is useful for limiting the scope of the cookie to specific parts of a website.
Let’s say we want to create a cookie that stores a user’s name and expires after 24 hours. We can do this using the following code:
1 2 3 | const name = "John"; const expires = new Date(Date.now() + 86400e3).toUTCString(); // 24 hours from now document.cookie = `name=${name}; expires=${expires}; path=/`; |
This code creates a cookie with the name name
and the value John
, which will expire after 24 hours. The path
parameter is set to /
, which means the cookie will be valid for the entire website.
Examples
Here are some additional examples to demonstrate how to store data in a cookie using JavaScript.
Example 1: Storing a single value in a cookie
Suppose we want to store a user’s preferred language in a cookie. Here’s how we can do it:
1 2 3 | function setLanguageCookie(lang) { document.cookie = `lang=${lang};path=/`; } |
In the above code, we define a function setLanguageCookie
that takes a lang
parameter (the language code) and sets a cookie with the name lang
and value equal to lang
. We also specify the path
attribute as /
to ensure that the cookie is accessible from any page on the website.
Example 2: Storing multiple values in a cookie
Sometimes we may need to store multiple values in a cookie. We can achieve this by serializing the data into a string (using JSON.stringify) and storing it in the cookie.
1 2 3 4 5 | function setUserInfoCookie(name, email, age) { const userInfo = { name, email, age }; const userInfoString = JSON.stringify(userInfo); document.cookie = `userInfo=${userInfoString};path=/`; } |
In the above code, we define a function setUserInfoCookie
that takes the user’s name, email, and age as parameters. We first create an object userInfo
with these values and then serialize it into a string using JSON.stringify
. Finally, we set a cookie with the name userInfo
and value equal to userInfoString
.