What is a session?
A website has no built-in way to remember who you are from one page to the next. Every click sends a brand new request from your browser to the site’s server. The server treats each one like it’s never seen you before, which is what developers mean when they say requests are stateless. A session is how the site keeps track of you between clicks, so you stay logged in and your cart keeps its items as you move around.
Websites can save small bits of text called cookies in your browser, which sends them back to the site with every request. The server starts a session the first time you visit and saves a long random string called a session ID in a cookie. It ties the session to your account when you log in, so every click after that tells the server who you are.
The server usually keeps session data on the backend in a database. A lot of apps use Redis for this because it keeps everything in memory, which makes lookups fast. Some frameworks like Rails skip the lookup and keep the whole session inside the cookie itself. Rails signs and encrypts it so you can’t read or change what’s in it.
Sessions end when you log out or after you’ve been inactive for a while, which is why your bank logs you out after a few minutes of doing nothing. Anyone who steals your session ID can act as you until it expires, so sites work hard to keep it secret.