Skip to content

Instantly share code, notes, and snippets.

@dwayne
Created July 31, 2015 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwayne/309ed557819ef8a129d0 to your computer and use it in GitHub Desktop.
Save dwayne/309ed557819ef8a129d0 to your computer and use it in GitHub Desktop.
Understanding HTTP Cookies

I will use the simple Sinatra application below to explain.

First, we run the app.

$ ruby app.rb

This launches a server at localhost:4567.

  1. Open your browser at http://localhost:4567.
  2. Enter your name, say Dwayne, and click Set.
  3. Doing so causes your browser to send a POST request to /set with name=Dwayne.
  4. The corresponding route handler then "sets a cookie" under the name name with value Dwayne.
  5. What really happens is that the Set-Cookie header is set with name=Dwayne.
  6. The redirect is executed causing a 303 status and at least the Set-Cookie and Location headers to be sent to the browser.
  7. The browser stores the cookie and will send it via the COOKIE header with any subsequent request, which happens to be now.
  8. You see, the 303 redirect causes the browser to immediately make another request to the URL given in the Location header, /. Hence, the cookie information will be sent along.
  9. The corresponding route handler then fetches the relevant cookie and displays the appropriate message.

References

require 'sinatra'
get '/' do
@name = request.cookies['name'] || 'world'
erb :index
end
post '/set' do
response.set_cookie('name', params[:name])
redirect to('/')
end
source 'https://rubygems.org'
gem 'sinatra'
gem 'thin'
<p>
Hello, <%= @name %>!
</p>
<form action="/set" method="POST">
<label>
What's your name?<br>
<input type="text" name="name">
</label>
<button type="submit">Set</button>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment