Home/Blog/Web Development/What are HTTP cookies?
Home/Blog/Web Development/What are HTTP cookies?

What are HTTP cookies?

9 min read
Oct 29, 2021

One way or another, 4.66 billion people actively use the internet and interact with HTTP cookies every day. In many ways, HTTP cookies provide you with a streamlined and personalized website experience, and for some, these services are often overlooked or misunderstood.

Aside from the user end, HTTP cookies allow web developers to create more personalized and convenient website visits for their users. Aside from the benefits that HTTP cookies offer, there are security concerns also to consider. More commonly discussed in the past couple of years, many individuals concern themselves with personal information privacy and security.

No matter your background knowledge on HTTP cookies, we hope to provide a comprehensive post on how HTTP cookies work. Here’s what we’ll cover today:


What are HTTP cookies?

How to create HTTP cookies

HTTP cookie properties

HTTP cookie types

Wrapping Up



Get hands-on with Web Application Security for free Learn the fundamentals of Web Application Security with Educative’s 1-week free trial.

Web Application Security: Understanding HTTP Security Headers


What are HTTP cookies?#

Cookies are small pieces of data used as a storage medium in the browser and sent to the server with each request. They are helpful for session management, user personalization, and tracking.

Session management:

Session management facilitates secure interactions between the user and some service or application. As the user continues to interact with the web application, they submit requests that help track the user’s status during the session.

Examples: Logins, auto-filled form fields, shopping lists

User personalization:

User personalization retains user preferences and settings for reapplication upon user login or application start. Settings are saved and synchronized with a central database to help users return to preferred settings used during their first application interaction.

Examples: User preferences, themes, language

Tracking:

Tracking records and analyzes users’ web browsing habits and finds the number and type of pages the user visits. Details include time spent on page and page sequence across a user’s sessions. Due to the sensitive information behind tracking, users should be aware of vulnerabilities from visiting insecure web pages.

Example: Ad tracking


How to create HTTP cookies#

There are two ways to create HTTP cookies. Whether through Google Chrome or Mozilla Firefox, you can type in Javascript code to set the cookie into the console with any browser you access. The other option involves the web server sending one or more set-cookie headers.

1. Client-side

After opening the console, you can set a cookie with JavaScript by typing out the code:

document.cookie="example=1"

In order to check if your cookie is set up, open up the “Application” tab and click the “Cookies” tab to access your new cookie. Here’s a picture to show what you should see:

widget

2. Web server-side

In the case where you wish to build your own website, you can create a HTML script where a button creates a cookie.

<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-compatible" content ="ie=edge">
<title>Document</title>
</head>
<body>
<button id = 'btnCreateCookie'>Create Cookie </button>
<script>
const btnCreateCookie = document.getElementbyID("btnCreateCookie")
btnCreateCookie.addEventLister("click", e=> document.cookie = "example-3")
</script>
</body>
</html>

Once you have the HTML file ready, you can create an index.js application that will return the HTML file using an Express application for Node.js.

const app = require("express")()
app.get("/", (req, res) => {
res.sendFile(`${__dirname}/index.html`)
})
app.listen(8080, ()=>console.log("listening on port8080"))

You’ll notice that every time you click the button on your website, you will create a cookie by the name “example-3”.

In the case where you want your server to set a cookie without manually writing out JavaScript, you can pass an array of cookies.

const app = require("express")()
app.get("/", (req, res) => {
res.setHeader("set-cookie", ["setfromserver=1"])
res.sendFile(`${__dirname}/index.html`)
})
app.listen(8080, ()=>console.log("listening on port8080"))

By having the browser set the cookie, you won’t have to manually type in JavaScript to create a cookie for each visitor.


No matter the type of cookie, cookie properties remain consistent across all cookie types. The cookie properties you should take note of include:

  1. Cookie scope

The scope of a cookie determines what URLs cookies should be sent to. The scope of a cookie splits into two different attributes:

  • Domain

More simply put, domains attributes are “buckets” in which cookies are placed. Each cookie assigns itself to a unique domain name, which helps keep cookies organized and specific to the pages users enter.

Here’s an example:

Domain=example.io will set cookies to be available for on all subdomains such as developer.example.io

  • Path

The path attribute indicates a specific URL path to send the cookie header. In order to set cookies for different paths, you can write the code:

document.cookie="examplepath1=1; path=/path"

document.cookie="examplepath2=2; path=/blog"

Now, when you enter a website via any URL with /path, such as https://www.example.io/path/, you will send a cookie header "educativepath1=1".

Just as another example, if you were to enter a website via any URL with /blog, such as https://www.example.io/blog

You will send a cookie header "educativepath2=2".

Other requested paths such as:

/bloglearn

/pathlearn

/learnpath

will not send a cookie header unless a path attribute is set up for these URLs.

  1. Expires and Max-age

Another property to consider is the lifetime of a cookie or, more simply, the cookie’s expiration date. The Expires and Max-Age attributes fall under a persistent cookies category. Despite the name “permanent cookie,” the Expires attribute will delete a cookie at a specified date. In contrast, the Max-Age attribute will delete a cookie after a specified period of time.

On the other hand, session cookies are deleted when the current session ends. Keep in mind that some browsers define when that current session ends, which can be an indefinite amount of time.

  1. SameSite

We covered earlier how HTTP cookies are set for direct URLs, but what about clicking a link within that direct URL? When clicking a link within a page, your cookies can be sent from the new page you are directed to. This is where the SameSite attribute comes into play. Put simply, Samesite specifies whether cookies are sent with cross-site requests or whenever you click a link on any given page. For example, let’s follow this sequence for how cookies are sent and received when navigating between one web page to another.

  1. You type in the URL www.example.com
  2. You will receive a first-party cookie
  3. On www.example.com, you click a link or button that sends a Fetch request to www.cookie.com.
  4. www.cookie.com sets a cookie with Domain=cookie.com
  5. www.example.com now holds a third-party cookie from www.cookie.com.

A SameSite attribute specifies whether third-party cookies are sent with three values:

  • Strict

With a SameSite value of strict, cookies will only be sent through a first-party cookie context and not third-party cookies.

  • Lax

With a SameSite value of lax, cookies will only be sent when users actively click a link to a third-party website. If the SameSite attribute isn’t directly set, lax becomes the default value.

  • None

With a SameSite value of None, cookies will be sent in all contexts.


Give yourself an edge at your next interview.#

With Educative Unlimited, you can access hundreds of courses tailor-made for software developers for less than $17 a month. Stay on the cutting edge by taking interview prep courses designed by industry experts at top tech companies.

Get started with a FREE 1-week trial today


Session cookies

Also known as temporary cookies, session cookies expire once you close or leave the browser. You’ll notice a website is using session cookies when you have to enter your login credentials every time you open the page.

One example to consider is the shopping cart on any eCommerce site. Session cookies help keep items in the shopping cart when you click an item to open a new tab. Without session cookies, the website would not remember the items you clicked on previously.

First-Party cookies

First-party cookies are stored directly on your computer by the website you are visiting. The website collects analytics and helpful information to improve your user experience.

One use case to consider is the example given earlier in this blog post. When accessing a website such as www.example.com, the website will send a request to your computer that provides a unique cookie value under the domain www.example.com. Without first-party cookies, websites won’t automatically log you in or remember your preferences from past sessions.

Third-Party cookies

Third-party cookies are created by domains other than the one you directly access. Generally used for tracking purposes, third-party cookies are stored even after the browser is closed. One common use case involves ad tracking from websites other than the ones you visit. For example, when browsing through various product pages on an eCommerce website, you might be exposed to third-party cookies from a domain outside of the specific website you visited. Later on, when you close your browser, a third-party cookie can be used to track whether or not you bought the product you saw on the website.

Specific pictures pulled from a third-party website outside the particular domain you are on can contain third-party cookies that give other domains the ability to send targeted emails or ads for an item you looked at but didn’t purchase.

Secure cookies

Secure cookies prevent unauthorized parties from observing cookies sent to a new user within an HTTP response. With the Secure attribute, HTTP requests will only include the cookie if transmitted over a secure channel.

HttpOnly cookies Initially implemented by Microsoft Internet Explorer developers in 2002, HttpOnly flags can be included in a Set-Cookie HTTP header. The HttpOnly attribute mitigates the risk of users accidentally accessing a link that may exploit a cross-site scripting flaw.

Cross-site scripting attacks are malicious scripts added to a trusted website that gives attackers access to cookies and other sensitive information.

Zombie cookies

Somewhat indicated by the name, zombie cookies are cookies that come back to life even when deleted or the browser is closed. Zombie cookies store themselves in places outside of the web browser’s dedicated cookie storage. When the user destroys a cookie, a zombie cookie can take the replica stored elsewhere and attach it to the user’s cookie storage again.

Historically, ad companies such as Quantcast were sued for using zombie cookies to track users and store personal information. States like California deem the use of zombie cookies as an illegal invasion of privacy.


Wrapping up#

Congrats on taking your first steps with HTTP cookies! HTTP cookies have been around for a long time and hold many opportunities to improve user experience and authentication.

While we covered the basics of HTTP cookies, there’s still so much more to learn about HTTP cookie security, such as:

  • HTTP Security Headers
  • X XSS Protection
  • Testing for Security Headers To learn these concepts and more, check out Educative’s course Web Application Security: Understanding HTTP Security Headers. In this hands-on course, you’ll cover topics ranging from HTTP Strict Transport Security, the state of HTTP security, and more. By the end, you’ll have learned how to increase security using web controls such as HTTP headers and ensure that you’re up to date with security controls. Happy learning!

Continue reading about web development:#


 
Join 2.5 million developers at
Explore the catalog

Free Resources