Understand how HTTP cookies work

Cookies are an essential part of the Web because they allow conversations and can usually identify users during navigation


By using Cookies, we can exchange information between the server and the browser to provide a way to customize user sessions and allow the server to identify users between requests.

HTTP is stateless, which means that all request sources to the server are exactly the same, and the server cannot determine whether the request comes from a client that has made a request before, or whether it is a new request.

When the HTTP request starts, the browser sends the cookie to the server, and then sends the cookie back from the server, which can edit its content.

Cookies are essentially used to store the session ID.

In the past, because there was no other choice, cookies were used to store various types of data. But nowWeb Storage API(Local storage and session storage) andIndex database, We have a better choice.

Especially because the limit of the data that cookies can save is very low, because cookies are sent back and forth to our server for each HTTP request, including images or CSS /JavaScriptfile.

Cookies have a long history. The first version was released in 1994. Over time, they were standardized in multiple RFC versions.

RFC stands for "Soliciting Comments", which is the method defined by the Internet Engineering Task Force (IETF). IETF is the entity responsible for setting standards for the Internet

The latest specifications for cookies are inRFC 6265, which is dated 2011.

Limitations of Cookies

  • Cookies can only be stored4KB data
  • Cookies arePrivate domain. The website can only read the cookies set by it, but not the cookies of other domains
  • Each domain can limit up to 20 cookies (but the specific number depends on the specific browser implementation)
  • The total number of cookies is limited (but the exact number depends on the specific browser implementation). If this number is exceeded, the new cookie will replace the old cookie.

Cookie can be set or read server side or client side.

On the client side, cookies are made byFile objectAsdocument.cookie

Set cookies

The simplest example of setting a cookie is:

document.cookie = 'name=Flavio'

This will add the new cookie to the existing cookie (it will not overwrite the existing cookie)

Cookie value should be url-encodedencodeURIComponent()To ensure that it does not contain any spaces, commas or semicolons that are invalid in the cookie value.

If you do not make other settings, the cookie will expire when the browser is closed. To avoid this, please add an expiration date in UTC format (Mon, 26 Mar 2018 17:04:05 UTC)

document.cookie = 'name=Flavio; expires=Mon, 26 Mar 2018 17:04:05 UTC'

A simple JavaScript snippet can set a cookie that expires within 24 hours. It is:

const date = new Date()
date.setHours(date.getHours() + 24)
document.cookie = 'name=Flavio; expires=' + date.toUTCString()

Or you can usemax-ageThe parameter sets the expiration time in seconds:

document.cookie = 'name=Flavio; max-age=3600' //expires in 60 minutes
document.cookie = 'name=Flavio; max-age=31536000' //expires in 1 year

ThispathThe parameter specifies the document location of the cookie, so it is assigned to a specific path and only sent to the server if the path matches the current document location or parent:

document.cookie = 'name=Flavio; path=/dashboard'

The cookie is sent/dashboard,/dashboard/todayAnd other sub URLs/dashboard/, But not in/postsE.g.

If you do not set the path, it will default to the current document location. This means that to apply global cookies from internal pages, you need to specifypath=/.

ThisdomainCan be used to specify a subdomain for your cookie.

document.cookie = 'name=Flavio; domain=mysite.com;'

If it is not set, even if a subdomain is used, it defaults to the host part (if on subdomain.mydomain.com, it is set to mydomain.com by default). The domain cookie is contained in the subdomain.


Add toSecureThe parameters ensure that cookies can only be transmitted securely over HTTPS and will not be sent over an unencrypted HTTP connection:

document.cookie = 'name=Flavio; Secure;'

Please note that this will not ensure the safety of the cookie in any way-always avoid adding sensitive information to the cookie


A useful parameter isHttpOnly, Which makes it impossible to access cookies throughdocument.cookieAPI, so they can only be edited by the server:

document.cookie = 'name=Flavio; Secure; HttpOnly'


SameSite, Unfortunately, not all browsers support (but many browsers support!)https://caniuse.com/#feat=same-site-cookie-attribute, So that the server requires cookies not to be sent on cross-site requests, but only on resources with the cookie domain as the source, which should be of great help in reducing the risk of CSRF (cross-site request forgery) attacks.

To update the value of the cookie, simply assign a new value to the cookie name:

document.cookie = 'name=Flavio2'

Similar to updating the value, to update the expiration date, reassign the new valueexpiresormax-ageproperty:

document.cookie = 'name=Flavio; max-age=31536000' //expires in 1 year

Just remember to also add any other parameters you added first, such aspathordomain.

To delete a cookie, unset its value and pass the date in the past:

document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'

(Again, use all the parameters you used to set it up)

Access Cookies value

To access cookies, look fordocument.cookie:

const cookies = document.cookie

This will return a string containing all cookies for the page, separated by semicolons:

'name1=Flavio1; name2=Flavio2; name3=Flavio3'
if (
  document.cookie.split(';').filter(item => {
    return item.indexOf('name=') >= 0
) {
  //name exists

//ES2016 if ( document.cookie.split(’;’).filter(item => { return item.includes(‘name=’) }).length ) { //name exists }

Abstract library

There are many different libraries that will provide a more user-friendly API to manage cookies. One of them ishttps://github.com/js-cookie/js-cookie, It supports IE7 at most, and has a lot of stars on GitHub (always good).

Some examples of its usage:

Cookies.set('name', 'value')
Cookies.set('name', 'value', {
  expires: 7,
  path: '',
  domain: 'subdomain.site.com',
  secure: true

Cookies.get(‘name’) // => ‘value’ Cookies.remove(‘name’)

//JSON Cookies.set(‘name’, { name: ‘Flavio’ }) Cookies.getJSON(‘name’) // => { name: ‘Flavio’ }

Should I use the native Cookies API?

All of this comes down to adding more kilobytes of downloads per user, so this is your choice.

Use Cookies on the server side

Every environment used to build an HTTP server allows you to interact with cookies, because cookies are the foundation of the modern web, and without cookies, too many environments cannot be built.

PHP $_COOKIE Go innet/httpStandard library

and many more.

Let's use Node.js as an example

When using Express.js, you can useres.cookieAPI:

res.cookie('name1', '1Flavio', {
  domain: '.example.com',
  path: '/admin',
  secure: true
res.cookie('name2', 'Flavio2', {
  expires: new Date(Date.now() + 900000),
  httpOnly: true
res.cookie('name3', 'Flavio3', { maxAge: 900000, httpOnly: true })

//takes care of serializing JSON res.cookie(‘name4’, { items: [1, 2, 3] }, { maxAge: 900000 })

To parse cookies, a good option is to usehttps://github.com/expressjs/cookie-parserMiddleware. The cookie information of each Request object will be inreq.cookieproperty:

req.cookies.name //Flavio
req.cookies.name1 //Flavio1

If you use the following method to create a cookiesigned: true:

res.cookie('name5', 'Flavio5', { signed: true })

They will be atreq.signedCookiesObject. Signed cookies can prevent modification on the client side. The signature used to sign the cookie value ensures that you can know on the server side whether the client has modified it.

https://github.com/expressjs/sessionwithhttps://github.com/expressjs/cookie-sessionThere are two different middleware options that can be used to build cookie-based authentication, which option to use according to your needs.

Use browser DevTools to check cookies

All their browsersdevelopment toolsProvide an interface for checking and editing cookies.

Chrome alloy

Chrome devtools cookies

Firefox browser

Firefox devtools cookies


Safari devtools cookies

Alternatives to Cookies

Are cookies the only way to establish authentication and sessions on the Web?

Do not! Recently there is a popular technique calledJSON web token(JWT),This is anToken-based authentication.

Download mine for freeJavaScript beginner's manual

More browser tutorials: