Course contentsShow
← Web Development
Lesson 798 of 2,98214. Browser StorageFree lesson

Setting Cookies with document.cookie

Learn the basic syntax for creating cookies using JavaScript's document.cookie API and key-value pair formatting.

Setting Cookies with document.cookie

What you'll learn: You'll learn how to create cookies using JavaScript's document.cookie API with simple key-value pair syntax.


The Basic Syntax

Unlike localStorage's straightforward setItem() method, setting cookies in JavaScript uses a somewhat unusual approach: you assign a specially formatted string directly to document.cookie. The basic pattern looks like this:

document.cookie = "username=JohnDoe";

This creates a cookie named username with the value JohnDoe. Notice the syntax: it's a single string containing the key-value pair separated by an equals sign.

The Key-Value Format

Think of document.cookie as a special mailbox. Instead of replacing what's inside when you write to it, it adds your new cookie to the collection. Each cookie must follow this format:

document.cookie = "theme=dark";
document.cookie = "language=en";
// Both cookies now exist

Each assignment creates or updates one cookie. The name comes before the = sign, the value after it.

Important Quirks

When you read document.cookie, you get all cookies as one string:

console.log(document.cookie);
// Might show: "username=JohnDoe; theme=dark; language=en"

But when you write to it, you only set one cookie at a time. This asymmetry takes some getting used to—it's like writing individual notes but reading them all as one combined message.


Key Takeaway: Use document.cookie = "name=value" to create or update a single cookie, following strict key-value pair formatting where the cookie name and value are separated by an equals sign.