ArticleZip > Pure Javascript Store Object In Cookie

Pure Javascript Store Object In Cookie

When it comes to web development, working with cookies is a common task. Cookies are small pieces of data stored on a user's computer by the browser to track information about the user's session. Storing objects in cookies can be especially valuable when you want to save and retrieve complex data structures in your JavaScript applications. In this article, we'll walk you through how to store a JavaScript object in a cookie using pure JavaScript.

Before diving into the code, it's essential to understand the process. By default, cookies can only store strings, so we need to serialize our JavaScript object into a JSON string before storing it in a cookie. When we retrieve the cookie value, we'll need to deserialize the JSON string back into a JavaScript object.

Let's start by creating a function to store a JavaScript object in a cookie. Below is a simple example function that takes an object as a parameter, serializes it into a JSON string, and sets it as a cookie:

Javascript

function setCookie(name, value, days) {
  const expires = new Date();
  expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
  document.cookie = `${name}=${JSON.stringify(value)};expires=${expires.toUTCString()};path=/`;
}

In this function, `name` is the name of the cookie, `value` is the JavaScript object you want to store, and `days` is the number of days until the cookie expires. We convert the JavaScript object into a JSON string using `JSON.stringify()` before setting it as the cookie value.

Next, let's write a function to retrieve the JavaScript object from the cookie. This function will deserialize the JSON string back into a JavaScript object. Here's the code:

Javascript

function getCookie(name) {
  const cookieValue = document.cookie.match(`(^|;)\s*${name}\s*=\s*([^;]+)`);
  return cookieValue ? JSON.parse(cookieValue.pop()) : null;
}

In this function, `name` is the name of the cookie we want to retrieve. We use a regular expression to extract the cookie value and then parse it back into a JavaScript object using `JSON.parse()`.

Once you have these functions in place, you can use them to store and retrieve JavaScript objects in cookies. Here's an example of how you can use these functions:

Javascript

const user = { id: 1, name: 'John Doe', email: 'johndoe@example.com' };
setCookie('user', user, 7);

const storedUser = getCookie('user');
console.log(storedUser);

In this example, we first create a `user` object, store it in a cookie named `'user'`, and set the cookie to expire in seven days. We then retrieve the `user` object from the cookie using the `getCookie` function and log it to the console.

By following these simple steps and using pure JavaScript, you can easily store and retrieve JavaScript objects in cookies, making your web applications more dynamic and user-friendly. Happy coding!

×