First steps with Cookies in JavaScript

- 👤 Andrés Cruz

🇪🇸 En español

First steps with Cookies in JavaScript

Many times we want to save some information about our user visiting a web page but for various reasons, server-side technologies are not desired.

When using other technologies like Android, desktop applications, or any server-side application, it's easier to answer the need to save information persistently in files and/or databases; with JavaScript, we have some similar solutions like Cookies.

Cookies are small files that are stored on web pages.

JavaScript has several persistent technologies (meaning the information we want to store remains even when the user closes or refreshes their browser window) such as SQLite and Cookies, which we will cover in this post.

Saving information in the browser can be as simple as writing a single line of code... or as complicated as not understanding why your cookie isn't deleted even though you swear you removed it. In this guide, I'll explain what cookies are in JavaScript, how to create, read, update, and delete them, and especially how to use them in real-world situations, just like I do when I want to avoid bombarding my API every two seconds asking for user data that WILL NOT change.

What are cookies in JavaScript and what are they for?

Cookies are small text strings that the browser saves persistently. They were born in the world of the HTTP protocol, but today, from JavaScript, we can manipulate them without problems using document.cookie.

Unlike other browser storage technologies, cookies are automatically sent to the server with every request. That's why they are typically used for authentication, sessions, and user preferences.

How cookies work in the browser

  • Each cookie is a key=value pair with additional attributes: expiration date, path, domain, whether it should be secure, etc.
  • When you access document.cookie, you get all the cookies for the domain separated by a semicolon.
nombre=andres; usuario=acy; theme=dark

When to use cookies and when NOT to use them

✔️ Use cookies when:

  • You need the information to travel to the server (sessions, auth).
  • You want to remember the user between visits.
  • You need to control time-based expiration.

✖️ Do not use cookies when:

  • You are storing large data (limit ≈ 4KB).
  • It is sensitive information (better httpOnly from the server).
  • You don't need the data to travel with every request.
    In those cases: localStorage or sessionStorage.

Cookies in JavaScript

You've surely heard about cookies many times; when you enter a website, a message appears like the following: "This site, like most, uses cookies. If you continue browsing, we understand that you accept the cookie policy."

But perhaps you haven't paid much attention to it yet; don't worry; this post offers an introduction to using Cookies with JavaScript.

Getting started with Cookies using native JavaScript

In this section, we will look at the most typical functionalities to perform with Cookies.

How to create cookies in JavaScript

To create Cookies, we must use the key=value scheme:

document.cookie="key=value;"

Accessing Cookies

To access all Cookies from the current position, we can use the following JavaScript:

document.cookie;

For our example (which we will see a little later), it gives a result like the following:

"nombre=andres; usuario=acy;"

Cookie Examples

We will create a couple of Cookies to experiment with them; the first Cookie indicates the person's name and another Cookie to indicate the user, which will be requested from the user using a JavaScript `prompt`:

    // example largely taken from http://www.w3schools.com/js/js_cookies.asp 
    
    function setCookie(cname, cvalue) {
        document.cookie = cname + "=" + cvalue + "; ";
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ')
                c = c.substring(1);
            if (c.indexOf(name) == 0)
                return c.substring(name.length, c.length);
        }
        return "";
    }

    function checkCookie() {
        var nombre = getCookie("nombre");
        var usuario = getCookie("usuario");
        if (nombre != "" && usuario != "") {
            alert("Hola " + nombre + " tu usuario es: " + usuario);
        } else {
            nombre = prompt("Da tu nombre:", "");
            if (nombre != "" && nombre != NULL) {
                setCookie("nombre", nombre);
            }
            usuario = prompt("Da tu usuario:", "");
            if (usuario != "" && usuario != NULL) {
                setCookie("usuario", usuario);
                alert("refresca la página");
            }
        }
    }
    checkCookie();

See demo

What you should try in the previous example is to provide your name and a user and refresh the page.

Once the previous steps are completed, you will see that the browser "remembers" the previously entered name and user; with this small example, you can demonstrate the basic use of cookies and from here explore a wide range of new possibilities to take our web applications to another level.

Cookie Expiration Date

Cookies can be given a useful lifespan so that once the date passes, they are simply deleted automatically:

document.cookie="nombre=andres; expires=Thu, 17 Dec 2026 12:00:00 UTC";

For this, we can use a scheme like the one presented in the W3C:

    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }

We specify the number of days we want our Cookie to last (with the `exdays` variable) and calculate the time from the current time `d.getTime()`, then all that remains is to specify the appropriate format:

var expires = "expires="+d.toUTCString();

Finishing the Cookie CRUD

So far we have seen how to create, access, and specify the lifespan of Cookies; we need to indicate how we can delete and modify existing ones.

Deleting Cookies.

In the previous section, we indicated how to define a lifespan for Cookies; we can use a date before the current one to delete Cookies that are no longer useful to us:

document.cookie="nombre=andres expires=Thu, 16 Dec 2026 12:00:00 UTC";

Typical problems when deleting them (based on real experience)

if the cookie was not deleted, it might be a path issue:

If you created it with path=/app, you must delete it with path=/app.

Modifying Cookies.

Cookies are modified exactly as they are created; that is:

document.cookie="nombre=andres";

How to read cookies in JavaScript

Reading cookies is as simple as consulting:

console.log(document.cookie);

Reading all cookies

const todas = document.cookie; 
console.log(todas);

Getting a specific cookie

We can extract it manually:

function getCookie(name) {
 const cookies = document.cookie.split(';');
 for (let c of cookies) {
   c = c.trim();
   if (c.startsWith(name + "=")) {
     return c.substring(name.length + 1);
   }
 }
 return null;
}

Optimized getCookie() utility function

function getCookie(name) {
 const match = document.cookie.match(
   new RegExp("(^|; )" + name + "=([^;]*)")
 );
 return match ? decodeURIComponent(match[2]) : null;
}

How to update and delete cookies

Updating is simply creating the same cookie with a new value:

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

Important attributes of a cookie

These attributes make the difference between a functional cookie and an insecure or incomplete one.

expires and max-age

They define how long the cookie lasts.

// 1 day 
document.cookie = "user=John; max-age=86400";

path

Controls on which paths the cookie will be accessible.

path=/

Is the most common.

domain

Allows sharing cookies between subdomains:

domain=mydomain.com

secure

The cookie only travels over HTTPS.

secure

You should always use it when saving any relevant data.

samesite

Helps prevent CSRF/XSRF attacks.

Values:

  • strict
  • lax (recommended by default)
  • none (requires secure)

httpOnly (important clarification)

Cannot be set from JavaScript.

It is set by the server and blocks JS access to the cookie, protecting sensitive data.

Example of saving basic user data (your experience)

In my projects, I usually save email, name, and purchased courses in cookies. Why?

Because that way I avoid making unnecessary queries to the API every time the user reloads the page.

Example based on that real use:

function saveUserBasicData({ email, nombre, cursos }) {
 document.cookie = `email=${email}; path=/; max-age=86400`;
 document.cookie = `nombre=${nombre}; path=/; max-age=86400`;
 document.cookie = `cursos=${encodeURIComponent(JSON.stringify(cursos))}; path=/; max-age=86400`;
}

Final Cookie Example

To finish, let's see an example where we use everything explained so far.

    >!--Demas JavaScript del ejemplo anterior--> 

    function deleteCookie() {
        document.cookie = "nombre=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
        document.cookie = "usuario=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    }

    function updateNombre() {
        nombre = prompt("Da tu nombre nuevamente:", "");
        if (nombre != "" && nombre != NULL) {
            setCookie("nombre", nombre);
        }
    }

    function updateUsuario() {
        usuario = prompt("Da tu usuario nuevamente:", "");
        if (usuario != "" && usuario != NULL) {
            setCookie("usuario", usuario);
        }
    }

Complete Examples in JavaScript

Here is a basic and clean CRUD that you can adapt to your applications:

function setCookie(name, value, days = 7) {
 const date = new Date(Date.now() + days * 864e5);
 document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${date.toUTCString()}; path=/`;
}
function getCookie(name) {
 const match = document.cookie.match(new RegExp("(^|; )" + name + "=([^;]*)"));
 return match ? decodeURIComponent(match[2]) : null;
}
function deleteCookie(name) {
 document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
}

Real example: remembering a light session without touching the API

In my projects, I usually do something like this:

function cacheUserSession(usuario) {
 setCookie("email", usuario.email, 1);
 setCookie("nombre", usuario.nombre, 1);
 setCookie("cursos", JSON.stringify(usuario.cursos), 1);
}
// I can then access it without touching the API: 
const email = getCookie("email");

Best practices and security when using cookies

  • Do not store sensitive data in cookies accessible from JS.
  • Use secure if your site is on HTTPS (always recommended).
  • Use samesite=lax as a general rule.
  • Do not store large objects (maximum ≈ 4KB per cookie).
  • Clean up cookies you no longer use to avoid unnecessary traffic.

Frequently Asked Questions

  • Can I store objects in a cookie?
    • Yes, but you must convert them to JSON and encode them.
  • What is the difference between cookies, localStorage, and sessionStorage?
    • Cookies: travel to the server; 4KB limit.
    • localStorage: persistent, does not travel to the server.
    • sessionStorage: is cleared when the tab is closed.
  • Can I delete a cookie without knowing its path?
    • No. You must use the same path it was created with.
  • Are cookies secure?
    • With secure + samesite + httpOnly (from the server), quite secure.

Plugin for Cookies in JavaScript

We see a very useful scheme for small sites that do not use many libraries and/or that we want to make few saves in cookies; The problem with working with Cookies natively is that it can be complex or become a real mess when we start updating variables, handling many variables or multiple queries to Cookies, and this is precisely because of the way they are stored, which is purely a String separated by semicolons (,).

To avoid the previous problem we can use a plugin that allows us to easily work with Cookies in JavaScript.

As you can see in the source code, the plugin is really small which means the loading impact for our website is minimal.

First steps with JavaScript Cookie

Once we include the JavaScript above, using it is really easy; simply use the Cookies variable as follows to store a value in a cookie:

Cookies.set('name', 'value');

To create a cookie with the value value, and since every set() method has its get(), to get the value we have:

Cookies.get('name'); // => 'value'

Setting the cookie's duration:

If we want to set a cookie's lifespan, for example, 7 days:

Cookies.set('name', 'value', { expires: 7 });

Deleting a cookie:

Finally, to remove a cookie:

Cookies.remove('name');

These are the main methods. You can also consult the official documentation at the GitHub link at the beginning of this post.

Conclusion

Cookies remain an essential tool when you need simple persistence + automatic communication with the server. They are limited in size but extremely useful for remembering the user, handling preferences, and avoiding unnecessary API calls, such as when I save email, name, or purchased courses.

With the examples, attributes, and best practices I showed you, you now have everything necessary to use them professionally.

See demo

I agree to receive announcements of interest about this Blog.

JavaScript has several persistent technologies (that the information we want to store is maintained even when the user closes or refreshes the browser window) such as SQLite and Cookies that we will discuss in this post.

| 👤 Andrés Cruz

🇪🇸 En español