Write Your First HTTP Cookie

Learn how to write and read an HTTP cookie

Cookies are set by the browser, often with a CGI or JavaScript. You can write a script to set a cookie at any event on a web page. Here's how to create cookies for your website.

Information Included in a Cookie

When you visit some web pages, you are given the option to set a cookie when you click another link. The cookie contains information about how the cookie works. This information includes:

  • Count=[number]: This is the name of the cookie.
  • expires=[time]: This details when the cookie expires.
  • path=/: This is the minimum path that needs to exist for the cookie to be returned.
  • domain=[website URL]: The domain that set the cookie. This is the only domain that can retrieve the cookie.
Website Cookies Concept
NiroDesign / Getty Images

Write the Cookie With JavaScript

Use the following code to write your cookie:

document.cookie = "count=1; expires=Wed, 01 Aug 2040 08:00:00 GMT; path=/; domain=lifewire.com";

Read Your Cookie

After you write the cookie, you need to read it to use it. Use this script to read the cookie:


Call Your Cookie in a Link or Button

Set your cookie when someone clicks a link with this code in your HTML body:

Set Cookie

This can be as simple or complex as you need. Since the cookie is set in plain JavaScript, it can be used, set, and accessed in any way you would access another JavaScript object. You can set and manage multiple cookies with JavaScript in a similar fashion.

mla apa chicago
Your Citation
Kyrnin, Jennifer. "Write Your First HTTP Cookie." ThoughtCo, Sep. 30, 2021, thoughtco.com/write-your-first-http-cookie-3466808. Kyrnin, Jennifer. (2021, September 30). Write Your First HTTP Cookie. Retrieved from https://www.thoughtco.com/write-your-first-http-cookie-3466808 Kyrnin, Jennifer. "Write Your First HTTP Cookie." ThoughtCo. https://www.thoughtco.com/write-your-first-http-cookie-3466808 (accessed March 27, 2023).