Cookies
suggest changeA cookie is a small piece of named data that a server asks the browser (or any HTTP client) to store and send back on later requests. Cookies are how the web remembers things between stateless HTTP requests: who is logged in, which theme you picked, what is in your cart.
The whole mechanism is two headers:
- the server sends
Set-Cookie: name=value; attributesin a response (one header per cookie) - the client sends
Cookie: name1=value1; name2=value2in later requests to matching URLs
The attributes in Set-Cookie control where and how long the cookie lives. The client never sends them back, only name=value pairs:
| Attribute | Meaning |
|---|---|
Path=/admin |
send only for URLs under /admin (default: the "directory" of the request path) |
Domain=example.com |
also send to subdomains; without it the cookie is host-only |
Max-Age=3600 / Expires=<date> |
persistent cookie; without them it is a session cookie dropped when the browser closes |
Secure |
send only over HTTPS |
HttpOnly |
hide from JavaScript (document.cookie) |
SameSite=Lax/Strict/None |
control sending on cross-site requests (CSRF protection) |
Partitioned |
store per top-level site (CHIPS), for third-party embeds |
This article covers building and parsing cookie headers, setting cookies on the server with WEBrick, Rack and Sinatra, and handling cookies on the client with Net::HTTP and the http-cookie gem. For login sessions built on top of cookies (signing, encryption, session stores) see Sessions.
The examples were run with Ruby 4.0, rack 3.2, rackup 2.3, webrick 1.9, http-cookie 1.1 and Sinatra 4.2:
gem install rack rackup webrick http-cookie sinatra rack-test
webrick hasn't shipped with Ruby since 3.0, and the old CGI::Cookie class was removed from the standard library in Ruby 4.0 (only cgi/escape is left), so use Rack's helpers instead.
Building and parsing cookie headers with Rack::Utils
Rack::Utils has low-level functions that work on header strings, and the rest of the Rack ecosystem builds on them:
require 'rack'
# Build Set-Cookie header values
puts Rack::Utils.set_cookie_header('theme', 'dark')
puts Rack::Utils.set_cookie_header('greeting', {
value: 'Zoë & co; ok',
path: '/',
domain: 'example.com',
expires: Time.utc(2030, 1, 1),
max_age: 3600,
secure: true,
httponly: true,
same_site: :strict,
partitioned: true
})
# Cookie names are restricted: no spaces, ';', '=' etc.
begin
Rack::Utils.set_cookie_header('user name', 'x')
rescue ArgumentError => e
puts "error: #{e.message}"
end
# Parse a Cookie request header (first value wins on duplicates)
header = 'theme=dark; greeting=Zo%C3%AB%20%26%20co%3B%20ok; theme=light'
p Rack::Utils.parse_cookies_header(header)
# A header that tells the browser to delete a cookie
puts Rack::Utils.delete_set_cookie_header('theme', path: '/')
theme=dark
greeting=Zo%C3%AB+%26+co%3B+ok; domain=example.com; path=/; max-age=3600; expires=Tue, 01 Jan 2030 00:00:00 GMT; secure; httponly; samesite=strict; partitioned
error: invalid cookie key: "user name"
{"theme" => "dark", "greeting" => "Zoë & co; ok"}
theme=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT
Things to notice:
- Values are percent-encoded, so
;,,, spaces and non-ASCII characters are safe. When reading, Rack decodes them back. If another system reads the cookie, it has to decode them the same way. - Names aren't encoded. An invalid name raises
ArgumentError, so stick to letters, digits,-and_. - When both
Max-AgeandExpiresare present, browsers useMax-Age.Expiresis only there for very old clients. - There is no "delete" instruction in HTTP. You delete a cookie by setting it again with an empty value and an expiry in the past.
- If a name appears twice in
Cookie(possible when cookies with different paths share a name), Rack keeps the first one. Browsers send the cookie with the longest path first.
Cookies with WEBrick
WEBrick has its own cookie class. req.cookies is an array of WEBrick::Cookie parsed from the request, and you append to res.cookies to send Set-Cookie headers. The example starts a server on a random free port (Port: 0) and talks to it with Net::HTTP:
require 'webrick'
require 'net/http'
server = WEBrick::HTTPServer.new(Port: 0, BindAddress: '127.0.0.1',
Logger: WEBrick::Log.new(File::NULL), AccessLog: [])
server.mount_proc '/visit' do |req, res|
# req.cookies is an Array of WEBrick::Cookie parsed from the Cookie header
seen = req.cookies.find { |c| c.name == 'visits' }
visits = seen ? seen.value.to_i + 1 : 1
cookie = WEBrick::Cookie.new('visits', visits.to_s)
cookie.path = '/'
cookie.max_age = 60 * 60 * 24 * 365
res.cookies << cookie
res.cookies << WEBrick::Cookie.new('lang', 'en')
res.body = "visit #{visits}\n"
end
port = server.config[:Port]
thread = Thread.new { server.start }
Net::HTTP.start('127.0.0.1', port) do |http|
res = http.get('/visit')
print res.body
p res.get_fields('set-cookie')
res = http.get('/visit', 'Cookie' => 'visits=41')
print res.body
end
server.shutdown
thread.join
visit 1
["visits=1; Max-Age=31536000; Path=/", "lang=en"]
visit 42
The second request shows the most important rule about cookies: the client decides what to send. A user can edit visits=1 to visits=41 in the browser's dev tools or with curl, and the server can't tell. Treat every cookie value as untrusted input.
WEBrick::Cookie knows only the old attributes (path, domain, expires, max_age, secure) and has no HttpOnly or SameSite. For real apps, run a Rack app on top of WEBrick (or Puma) instead, as in the next section.
A Rack app that sets, reads and deletes cookies
Rack::Response#set_cookie and #delete_cookie wrap the Rack::Utils functions, and Rack::Request#cookies returns a hash of the cookies the client sent. The file below is a small login app. It is served by WEBrick through the rackup gem, so the client examples later in this article can talk to a real local server:
# cookie_server.rb - a tiny Rack app served by WEBrick on a random local port
require 'rack'
require 'rackup'
require 'webrick'
require 'securerandom'
SESSIONS = {} # token => user name
APP = lambda do |env|
req = Rack::Request.new(env)
res = Rack::Response.new
case [req.request_method, req.path_info]
in ['POST', '/login']
token = SecureRandom.hex(16)
SESSIONS[token] = req.params['user']
res.set_cookie('sid', value: token, path: '/', httponly: true, same_site: :lax)
res.set_cookie('theme', value: 'dark', path: '/', max_age: 3600)
res.redirect('/account', 303)
in ['GET', '/account']
user = SESSIONS[req.cookies['sid']]
if user
res.write("hello #{user}, theme=#{req.cookies['theme'] || 'default'}\n")
else
res.status = 401
res.write("not logged in\n")
end
in ['POST', '/logout']
SESSIONS.delete(req.cookies['sid'])
res.delete_cookie('sid', path: '/')
res.write("bye\n")
in ['GET', '/echo']
res.write("Cookie: #{req.get_header('HTTP_COOKIE').inspect}\n")
else
res.status = 404
end
res.finish
end
def start_cookie_server
server = nil
ready = Queue.new
thread = Thread.new do
Rackup::Handler::WEBrick.run(APP, Host: '127.0.0.1', Port: 0,
Logger: WEBrick::Log.new(File::NULL),
AccessLog: []) do |s|
server = s
ready << true
end
end
ready.pop
port = server.config[:Port]
at_exit { server.shutdown; thread.join }
port
end
The sid cookie holds only a random token, and the real data (the user name) stays on the server in SESSIONS. That is the safe way to identify a user with a plain cookie: a 128-bit random token can't be guessed, and editing it just logs you out. Never put something like user_id=42 in a plain cookie.
Rack 3 stores several Set-Cookie values as an array in the response headers, and the server writes each one as its own header line. More on that in HTTP headers.
Handling cookies manually with Net::HTTP
Net::HTTP doesn't store cookies. If you only need to carry a cookie from one response to the next request, do it by hand. Take the Set-Cookie headers with get_fields (not [], which joins them with commas), keep the name=value part of each, and send them back in a Cookie header:
require 'net/http'
require_relative 'cookie_server'
port = start_cookie_server
http = Net::HTTP.new('127.0.0.1', port)
res = http.post('/login', 'user=alice')
puts "#{res.code} -> #{URI(res['location']).path}"
set_cookies = res.get_fields('set-cookie')
puts set_cookies
# Keep only "name=value" from each Set-Cookie and send them back
cookie_header = set_cookies.map { |c| c.split(';', 2).first }.join('; ')
puts "sending Cookie: #{cookie_header}"
print http.get('/account', 'Cookie' => cookie_header).body
print http.get('/account').body # no cookie => not logged in
303 -> /account
sid=3dd202eb6a0c19f657c24e71fd7ccf80; path=/; httponly; samesite=lax
theme=dark; path=/; max-age=3600
sending Cookie: sid=3dd202eb6a0c19f657c24e71fd7ccf80; theme=dark
hello alice, theme=dark
not logged in
This is fine for scripts that talk to one host. It ignores expiry, path, domain and Secure, and it doesn't handle cookies that are updated or deleted later. For anything longer than a couple of requests, use a cookie jar.
A cookie jar with the http-cookie gem
The http-cookie gem implements the browser rules from RFC 6265. HTTP::CookieJar#parse stores the cookies from a Set-Cookie header received from a given URI, and #cookies(uri) returns the cookies that should be sent to a URI. HTTP::Cookie.cookie_value turns them into a Cookie header. Mechanize and Faraday's cookie middleware use this gem.
Here is a minimal "browser" on top of Net::HTTP that keeps a jar and follows redirects:
require 'net/http'
require 'http-cookie'
require_relative 'cookie_server'
# A minimal "browser": Net::HTTP plus an HTTP::CookieJar
class Browser
attr_reader :jar
def initialize(jar = HTTP::CookieJar.new) = @jar = jar
def get(url) = request(Net::HTTP::Get, URI(url))
def post(url, form) = request(Net::HTTP::Post, URI(url), form)
private
def request(klass, uri, form = nil, redirects: 5)
req = klass.new(uri)
req.set_form_data(form) if form
cookie = HTTP::Cookie.cookie_value(@jar.cookies(uri))
req['Cookie'] = cookie unless cookie.empty?
res = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) }
res.get_fields('set-cookie')&.each { |value| @jar.parse(value, uri) }
if res.is_a?(Net::HTTPRedirection) && redirects > 0
return request(Net::HTTP::Get, uri + res['location'], redirects: redirects - 1)
end
res
end
end
port = start_cookie_server
base = "http://127.0.0.1:#{port}"
browser = Browser.new
print browser.post("#{base}/login", 'user' => 'alice').body
browser.jar.each do |c|
puts " #{c.name}: path=#{c.path} httponly=#{c.httponly?} session=#{c.session?}"
end
print browser.get("#{base}/echo").body
print browser.post("#{base}/logout", {}).body
puts "cookies left: #{browser.jar.map(&:name).inspect}"
print browser.get("#{base}/account").body
hello alice, theme=dark
sid: path=/ httponly=true session=true
theme: path=/ httponly=false session=false
Cookie: "sid=f1ffe12c61a0cd0ae193e00da70233db; theme=dark"
bye
cookies left: ["theme"]
not logged in
The login POST returns a 303 redirect along with two cookies. The jar stores them, and the redirected GET /account already carries them. On logout the server sends an expired sid cookie, and the jar removes it, just like a browser would. The same approach is used for Web scraping sites that require a login.
Path, domain and Secure rules in a jar
The jar decides which cookies go to which URL. This example makes the rules visible without a server, and also shows how to save a jar to disk:
require 'http-cookie'
require 'tmpdir'
jar = HTTP::CookieJar.new
uri = URI('https://shop.example.com/cart/items')
jar.parse('cart=3; Max-Age=86400; Path=/cart', uri)
jar.parse('prefs=compact; Domain=example.com; Path=/; Expires=Fri, 01 Jan 2049 00:00:00 GMT', uri)
jar.parse('sid=abc; Path=/; Secure; HttpOnly', uri) # no expiry: a session cookie
jar.parse('last=items; Max-Age=600', uri) # no Path: defaults to /cart
jar.parse('evil=1; Domain=other.com', uri) # rejected: wrong domain
def names(jar, url) = jar.cookies(URI(url)).map(&:name).sort
p names(jar, 'https://shop.example.com/cart/items')
p names(jar, 'https://shop.example.com/') # cart and last are limited to /cart
p names(jar, 'https://www.example.com/') # prefs covers all of example.com
p names(jar, 'http://shop.example.com/cart/x') # sid is Secure: not sent over http
p jar.cookies(uri).find { |c| c.name == 'last' }.path
Dir.mktmpdir do |dir|
path = File.join(dir, 'cookies.yml')
jar.save(path) # session cookies are skipped by default
p names(HTTP::CookieJar.new.load(path), 'https://shop.example.com/cart/')
jar.save(path, session: true) # keep them too
p names(HTTP::CookieJar.new.load(path), 'https://shop.example.com/cart/')
txt = File.join(dir, 'cookies.txt')
jar.save(txt, format: :cookiestxt, session: true) # Netscape format, usable with curl -b
File.foreach(txt) do |line|
fields = line.chomp.split("\t")
next unless fields.size == 7 # skip comments and blank lines
domain, _sub, path, secure, _expires, name, value = fields
puts [domain, path, secure, name, value].join(' ')
end
end
["cart", "last", "prefs", "sid"]
["prefs", "sid"]
["prefs"]
["cart", "last", "prefs"]
"/cart/"
["cart", "last", "prefs"]
["cart", "last", "prefs", "sid"]
shop.example.com /cart FALSE cart 3
#HttpOnly_shop.example.com / TRUE sid abc
shop.example.com /cart/ FALSE last items
.example.com / FALSE prefs compact
What the output shows:
- A cookie without
Pathgets the directory of the request path (/cart/here), not/. This is a common surprise: a cookie set by/cart/itemsis invisible on/. Always setpath: '/'explicitly unless you really want to limit it. - A cookie without
Domainis host-only: it goes toshop.example.combut notwww.example.com. WithDomain=example.comit goes to every subdomain. A server can't set cookies for an unrelated domain (other.com) or for a public suffix likecomorco.uk. Securecookies are never sent over plainhttp.saveskips session cookies unless you passsession: true, mirroring a browser that is closed and reopened.format: :cookiestxtwrites the Netscape format thatcurl -b cookies.txtandwget --load-cookiesread.HttpOnlycookies are written with a#HttpOnly_prefix.
Deleting a cookie: match the path and domain
A cookie is identified by its name, domain and path together. To delete (or overwrite) one, the Set-Cookie header must use the same path and domain it was created with. Otherwise the browser treats it as a different cookie, and the old one stays. Here the jar plays the browser:
require 'rack'
require 'http-cookie'
jar = HTTP::CookieJar.new # plays the role of the browser
uri = URI('https://shop.example.com/cart/checkout')
names = -> { jar.cookies(uri).map(&:name).sort }
jar.parse(Rack::Utils.set_cookie_header('coupon', { value: 'SAVE10', path: '/cart' }), uri)
jar.parse(Rack::Utils.set_cookie_header('promo', { value: 'x', path: '/', domain: 'example.com' }), uri)
p names.call
# Wrong: path and domain don't match the original cookie
jar.parse(Rack::Utils.delete_set_cookie_header('coupon'), uri)
jar.parse(Rack::Utils.delete_set_cookie_header('promo', path: '/'), uri)
p names.call
# Right: repeat the path and domain used when the cookie was set
jar.parse(Rack::Utils.delete_set_cookie_header('coupon', path: '/cart'), uri)
jar.parse(Rack::Utils.delete_set_cookie_header('promo', path: '/', domain: 'example.com'), uri)
p names.call
["coupon", "promo"]
["coupon", "promo"]
[]
The "wrong" deletions look harmless, but they create and immediately expire cookies with the default path and a host-only domain, and the originals survive. The easiest way to avoid this is to keep cookie options in one place (a constant or helper) and use it for both set_cookie and delete_cookie.
Cookies in Sinatra
Sinatra exposes the same Rack objects: request.cookies to read and response.set_cookie / response.delete_cookie to write. A cookie is a good place for non-sensitive preferences. This example stores a small JSON hash and shows how to read untrusted cookie data defensively. It is tested with rack-test, which keeps a cookie jar between requests:
ENV['APP_ENV'] = 'test'
require 'sinatra/base'
require 'rack/test'
require 'json'
class PrefsApp < Sinatra::Base
DEFAULTS = { 'theme' => 'light', 'per_page' => 20 }.freeze
helpers do
def prefs
data = JSON.parse(request.cookies['prefs'] || '{}')
data.is_a?(Hash) ? DEFAULTS.merge(data.slice(*DEFAULTS.keys)) : DEFAULTS
rescue JSON::ParserError
DEFAULTS # the client can send anything; never trust or crash on it
end
end
get '/' do
"theme=#{prefs['theme']} per_page=#{prefs['per_page']}\n"
end
post '/prefs' do
new_prefs = prefs.merge(params.slice('theme')) # allow-list what can be set
new_prefs['per_page'] = params['per_page'].to_i.clamp(10, 100) if params['per_page']
response.set_cookie('prefs', value: JSON.generate(new_prefs), path: '/',
max_age: 60 * 60 * 24 * 365, same_site: :lax)
redirect '/'
end
delete '/prefs' do
response.delete_cookie('prefs', path: '/')
redirect '/'
end
end
include Rack::Test::Methods
def app = PrefsApp
get '/'
print last_response.body
post '/prefs', theme: 'dark', per_page: '500', admin: 'true'
puts last_response.headers['set-cookie']
follow_redirect!
print last_response.body
set_cookie 'prefs=not-json'
get '/'
print last_response.body
set_cookie 'prefs=42'
get '/'
print last_response.body
delete '/prefs'
puts last_response.headers['set-cookie']
follow_redirect!
print last_response.body
theme=light per_page=20
prefs=%7B%22theme%22%3A%22dark%22%2C%22per_page%22%3A100%7D; path=/; max-age=31536000; samesite=lax
theme=dark per_page=100
theme=light per_page=20
theme=light per_page=20
prefs=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT
theme=light per_page=20
Notes:
- The cookie value is valid JSON on the way out, percent-encoded by Rack and decoded on the way in. There's no need to Base64 it.
- The reading side handles a cookie that is missing, not JSON, or JSON of the wrong type (
42), and it keeps only known keys. The writing side clampsper_pageand ignores unknown parameters likeadmin. - Users can still change the theme by editing the cookie, and that's fine. If changing a value would matter (a price, a role, a user id), store it on the server or in a signed or encrypted session. See Sessions.
- The
sinatra-contribgem adds acookieshelper (cookies[:theme] = 'dark'), but it is a thin wrapper over the same calls.
Security attributes and prefixes
For any cookie that identifies a user, set all of these:
res.set_cookie('__Host-sid', value: token, path: '/', secure: true,
httponly: true, same_site: :lax)
secure: truekeeps the cookie off plain HTTP, where anyone on the network could read it.httponly: truemeans an XSS bug can't read the cookie with JavaScript.same_site: :laxstops the browser from sending the cookie on cross-sitePOSTs, iframes andfetchcalls, which blocks most CSRF. Use:strictfor very sensitive cookies.same_site: :none(needed for third-party embeds) requiressecure: true.- The
__Host-name prefix is enforced by browsers. They accept such a cookie only if it hasSecure,Path=/and noDomain. That stops a compromised or malicious subdomain from overwriting your session cookie.__Secure-is the weaker version: it only requiresSecure. Ruby client libraries such ashttp-cookiedon't enforce the prefixes, only browsers do.
Limits to keep in mind: browsers store at least 4096 bytes per cookie (name, value and attributes together) and about 50 cookies per domain, and every cookie is sent with every matching request, including requests for images and CSS. Keep cookies few and small, and limit them with path when they are only needed in one part of the site.
Tips
- Read cookies as untrusted input: validate, allow-list and handle parse errors. A missing or garbage cookie should mean "use the default", not a 500 error.
- Identify users with a long random token (
SecureRandom.hex(16)or more) that maps to server-side data, or use Rack's encrypted session cookie. Never put a raw user id or role in a plain cookie. - Always set
path: '/'unless you mean otherwise, and reuse the exact samepathanddomainwhen deleting. - Set
Secure,HttpOnlyandSameSiteon anything sensitive, and consider the__Host-prefix. - Use
res.get_fields('set-cookie')on the client, neverres['set-cookie'], becauseExpiresdates contain commas. - For scripts that log in and make many requests, use
HTTP::CookieJarinstead of copying headers by hand. Save it to disk withjar.save(path, session: true)to reuse a login between runs. - Don't log
CookieorSet-Cookieheaders. They often hold credentials. See Application security for more.