Browser cookies keep small pieces of state that a browser can send back to a site on later requests. JavaScript can set and read a cookie for a non-sensitive preference that needs to be available to both page scripts and the server.
The document.cookie property reads the current page's script-accessible cookies as a semicolon-separated string. Assigning to it sets one cookie at a time, so a reader function must find the named cookie rather than treat the whole string as one value.
Cookies created by page scripts are readable by other scripts on the site. Authentication cookies belong on the server with HttpOnly and Secure protection; preferences that never need to reach the server usually fit localStorage better.
Steps to set and read cookies with JavaScript:
- Create index.html in a folder reserved for the demo using your text editor.
- index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Cookie preference</title> <style> body { font: 18px sans-serif; margin: 24px; } input, button { font: inherit; padding: 6px; } </style> <script src="cookies.js" defer></script> </head> <body> <h1>Cookie preference</h1> <label for="theme">Theme preference</label> <input id="theme" value="dark mode"> <p> <button id="save" type="button">Save preference</button> <button id="read" type="button">Read preference</button> </p> <p id="status" role="status">No cookie saved.</p> </body> </html>
The page has a preference field, separate save and read buttons, and a status message. The script loads after the HTML is parsed because its tag has the defer attribute.
- Create cookies.js beside index.html with the cookie-setting code.
- cookies.js
const preference = document.querySelector("#theme"); const status = document.querySelector("#status"); document.querySelector("#save").addEventListener("click", () => { const value = encodeURIComponent(preference.value); document.cookie = `site_theme=${value}; Max-Age=604800; Path=/; SameSite=Lax`; status.textContent = "Save requested. Click Read preference to check."; });
encodeURIComponent keeps spaces and separators inside the value. Max-Age=604800 sets a one-week lifetime, Path=/ makes the cookie available across this host's paths, and SameSite=Lax limits when it accompanies cross-site requests. Omitting Domain keeps it host-only. On an HTTPS site, the assignment should also include Secure; the local HTTP demo stores only a harmless preference.
- Append the cookie-reading function at the end of cookies.js.
function showPreference() { const prefix = "site_theme="; const cookie = document.cookie .split(";") .map((part) => part.trim()) .find((part) => part.startsWith(prefix)); status.textContent = cookie === undefined ? "No cookie saved." : `Read site_theme: ${decodeURIComponent(cookie.slice(prefix.length))}`; } document.querySelector("#read").addEventListener("click", showPreference); showPreference();
The exact site_theme= prefix avoids matching another cookie name. decodeURIComponent restores the original value, including its space. The final function call reads the cookie on each page load; attributes such as Max-Age are not included in the getter's result.
- Save index.html and cookies.js in your text editor.
- Start a local web server from the folder containing index.html with Python 3.
python3 -m http.server 8000 --bind 127.0.0.1
Cookies need an HTTP or HTTPS page rather than a file opened directly from disk. This command serves the current folder only on the local machine, so a folder containing just the demo avoids exposing unrelated files. The terminal stays open while the server runs.
- Open http://127.0.0.1:8000/index.html in your browser.
The page initially shows No cookie saved. in a browser with no existing site_theme cookie. localhost and 127.0.0.1 have separate cookies, so changing the host changes which cookie the page can read.
- Click Save preference to store the field's dark mode value.

- Click Read preference to retrieve the cookie through document.cookie.
The result should read Read site_theme: dark mode, with the space restored. No cookie saved. means the cookie is unavailable to the page, such as when site cookies are blocked.
- Reload the page with the browser's Reload button.

- Confirm that Read site_theme: dark mode still appears after the reload.
The page reads the stored cookie on load without another save. A changed hostname, cleared cookies, or an expired cookie produces No cookie saved. instead.