Intro to Cookies Module #37 Flashcards
When cookies are sent by the browser, where do they go?
To the server where they can be edited and sent back to the browser.
How much data can a cookie store?
4kb of data.
How many cookies can you set per domain?
20
Can cookies be set server side?
Yes, they can be set and read server side.
What is the basic syntax for setting a cookie
document.cookie = “name=Flavio” Adds a new cookie to whatever cookies already exist, cookies are not overwritten.
What values are not allowed in cookies?
Whitespace, comma, or semi colons are not valid.
What happens if you do not set an expiration date?
The cookie expires when the browser gets closed. Here is the syntax to set an expiration date:
document.cookie=”name=Flavio; expires=Mon, 27 May 2019 17:04:05”
What would the cookie syntax look like if you were to set it to expire in 24 hours?
First create a new date object, then set the hours to 24, then set the cookie so that the expire string has a value of date.toUTCString( )
const date = new Date( )
date. setHours(date.getHours( ) + 24)
document. cookie = “name=Flavio; expires=” + date.toUTCString( )
OR set a max-age param like so:
document. cookie = “name=Flavio; max-age=3600”//1 hour
document. cookie = “name=Flavio; max-age=”31536000” //1 year
What’s the syntax to set a path for a cookie location?
document.cookie = “name=Flavio; path=/dashboard
if you don’t set a path, the cookie defaults to the current location.
How would you set a global cookie from an inner page?
Set the path to: path=/
How would you make sure that the cookie is only securely transmitted over encrypted HTTPS?
Use the secure parameter with HttpOnly:
document.cookie = “name=Flavio; Secure; HttpOnly”
How can we update the value of a cookie?
simply change the value string as below:
document.cookie = “name=Roger” and update any other parameters. All of the original params must remain like path or domain.
Now how to delete a cookie?
Unset the name and expire it by setting it to a date in the past.
document.cookie = “name=; expires=Thu, 01 Jan 1970 00:00:00 UTC;”
How can we access the cookies once they have been created?
set the cookie to a variable and look it up with document.cookie as below:
const cookies = document.cookie
This will return a string of all the cookies set for the page using a semi colon separator
How can you access the value of a specific cookie?
There is no built-in way to do this but we can address this by writing our own functions. As below:
const getCookieValue = name => { const theCookie = document.cookie.split(';').filter(item => { if (item.includes(name + '=')) return true }) //better check to s if (theCookie.length ===0){return false} return theCookie[0].split('=')[1] } getCookieValue('the-cookies-name')