Session
Сессия
A web session lets an application remember a browser across separate requests, so a user can stay signed in or keep items in a cart while moving between pages.
Also known as: сессионная кука
Why web apps use sessions
After you sign in to a site, you expect to open your account settings without entering your password again. But HTTP doesn't remember who made the previous request. A session gives the application a way to connect requests to the same ongoing interaction. Sessions aren't just for signed-in users: a shop can use one to keep track of a guest's cart before checkout.
Follow a request
In a typical server-side setup, the application creates a session record and assigns it a cryptographically random ID. The record might contain an account ID and an expiration time. The browser gets only the ID, usually through a cookie. For example, the server might send this response header after sign-in:
Set-Cookie: sid=<random-id>; Path=/; Secure; HttpOnly; SameSite=Lax
When the browser later requests /account, it sends Cookie: sid=<random-id> if the cookie's rules permit it. The server looks up the record and checks that it's still valid. Knowing which account made the request is not the same as granting access: the app still has to check whether that account can perform the requested action. With several application instances, a shared store such as Redis lets any instance handle the lookup.
A session isn't a cookie
The session is the application's state across requests. The cookie in this example is how the browser carries the key to that state. In browser terminology, a session cookie is any cookie set without Expires or Max-Age, regardless of what it contains. It normally lasts for the browser session, but browsers that restore a previous session may restore its cookies too. Whether the server still accepts the ID is a separate decision.
What makes a session safe to use?
Treat a live session ID like a password: anyone who obtains it may be able to act as the signed-in user. Use HTTPS and mark the cookie Secure so the browser sends it only over a secure connection. HttpOnly blocks JavaScript from reading the cookie, but does not stop the browser from attaching it to requests. SameSite restricts when the cookie is sent in cross-site contexts and helps reduce CSRF risk; depending on the app, state-changing requests may also need defenses such as CSRF tokens.
Issue a fresh ID after login and invalidate the old one. On logout, invalidate the server-side record as well as clearing the cookie. Clearing the browser's copy alone doesn't make the ID unusable.
Interview questions
Interviewers often ask what happens if a browser sends a cookie for an expired session. The server treats the request as unauthenticated even though the cookie is still present. Be ready to distinguish an idle timeout, which resets when qualifying activity occurs, from an absolute lifetime, which ends the session even if the user stays active.