How it works
After a successful sign-in, the server creates a session record (user id, expiry, perhaps the device) in a database table or a fast store such as Redis, and sends back a long random session ID in a cookie. On each request the browser returns the cookie and the server looks the ID up to learn who is asking. The ID means nothing by itself, so reading it reveals nothing, but whoever holds it is treated as that user until it expires.
Because the truth lives on the server, control is simple: signing out, 'sign out of all devices', banning a user or changing their role takes effect on the very next request. The costs are a lookup on every request and a store that every server must share. Good practice is to mark the cookie HttpOnly (hidden from JavaScript), Secure (sent only over HTTPS) and SameSite (not sent from other sites, which blunts CSRF), to issue a fresh ID at sign-in, and to expire idle sessions.
Sessions pros and cons
Pros
- Instant sign-out and revocation, because the server owns the record
- The cookie holds only a random ID, so nothing sensitive sits in the browser
- HttpOnly cookies are out of reach of injected scripts
- A simple, long-proven model built into most web frameworks
Cons
- A lookup on every request, in a store all servers must share
- Cookies need CSRF protection and do not cross domains easily
- Awkward for mobile apps and third-party APIs that do not use cookies
When to use Sessions
Pick it when
- Websites and apps with their own backend on one domain
- You need to sign people out, ban them or change roles immediately
- Server-rendered frameworks such as Django, Laravel, Rails or Next.js
Skip it when
- Many independent services must verify users without a shared session store
Sessions vs the alternatives
Related terms
More in Auth and identity
Tokens and sessions