a cookie is a piece of data
that is set by the web server
but is stored by the web client
which sends it back to the server on every request
cookie data on the client is
so a cookie is often used not to store data directly, but as a key to a larger, long-term server-side database or
often that key identifies a currently logged-in user with a lot of related long-lived database records
Set-Cookie: ice_cream=chocolate
Cookie: ice_cream=chocolate; fruit=banana
Set-Cookie
Headername=value
, plus other options for this cookie separated by ;
sCookie
Headername=value
pairs separated by ;
sthe Fetch API does not always send cookies
(it's part of "same origin policy", enforcement of which is often draconian)
to send them you may need to set credentials: 'include'
like this
fetch('/articles.json', {credentials: 'include'})
.then(
WARNING: this is a security hole and you should only add
credentials: include
if you are having trouble getting cookies to work onlocalhost
; don't do it in production unless you have a good reason.
In Express, the incoming request's Cookie
header is available (via request.headers.cookie
), but it isn't pretty. Like URL-encoded parameters, it has to be parsed before it's useful.
Fortunately, Express has a middleware component called cookie-parser that parses the Cookie
header and puts all available cookies into an object at request.cookies
.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/', function(request, response) {
console.log('Cookies: ', request.cookies)
})
To set a cookie, use the method response.cookie():
response.cookie('cart', ['milk', 'cheese', 'dog food'])
Express will take care of encoding the value into JSON, and then URI-encoding that, to satisfy the arcane demands of the Cookie spec.
For a more detailed example,
cookie_counter.js
is a simple one-route Express "hit counter" which increments a hit count
on every request.
Run this...
git clone https://github.com/BurlingtonCodeAcademy/cookie-counter.git
cd cookie-counter
npm install
npm start
...then visit http://localhost:5000/cookie.html to see it in action. (Keep reloading the page!)
/