Server-Side Coding with JavaScript:
State: Cookies



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

Set-Cookie Header

  • set on the server response to the client
  • asks the client to create or modify a cookie for this
  • name=value, plus other options for this cookie separated by ;s

Fetch API vs Cookies

the 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'})

WARNING: this is a security hole and you should only add credentials: include if you are having trouble getting it to work on localhost; don't do it in production unless you have a good reason.

Sample Code

cookie_counter.js is based off our blog server, but adds a "hit counter" which it increments on every request.

run node cookie_counter.js and then visit http://localhost:5000/cookie.html to see it in action. (Keep reloading the page!)


comments powered by Disqus