Session
- In Turkish
- Oturum
In short
A session is a way for a server to remember a user across many requests, usually by keeping their data on the server and giving the browser a session ID.
What is a session in web development?
HTTP is stateless, which means each request stands on its own and the server does not automatically remember earlier ones. A session adds that memory: it is a period of interaction between one user and an application, typically from logging in to logging out, during which the server keeps track of who the user is and data such as the contents of their shopping cart.
In the classic server-side approach, when a user logs in the server creates a session record with their user ID and other data, stores it in memory, a database, or a cache such as Redis, and sends the browser a long random session ID in a cookie. The browser automatically includes that cookie with every later request, and the server uses the ID to look up the session. Logging out, or staying inactive past a timeout, deletes the session.
It works like a coat check: you hand over your coat and get a numbered ticket, and the ticket is only useful together with the counter that holds the coat. Because anyone who steals a session ID can impersonate the user, the cookie that carries it should be marked HttpOnly, Secure, and SameSite, and a new ID should be issued after login to prevent session fixation attacks.
Sessions are often confused with cookies and with token-based authentication. A cookie is just the transport that carries the session ID, while the session data itself lives on the server. With stateless tokens such as JWTs, the user's information travels inside a signed token, so the server doesn't need to look anything up, but the token is much harder to revoke before it expires.
Key takeaways
- Sessions let a server remember a user across stateless HTTP requests.
- The server stores session data and gives the client a random session ID.
- The session ID usually travels in an
HttpOnly,Securecookie. - A session ends when the user logs out or after an inactivity timeout.
- Server-side sessions are easy to revoke; stateless tokens like JWTs are not.
Example
// Using the express-session package
app.use(session({
secret: process.env.SESSION_SECRET, // signs the session ID cookie
resave: false, saveUninitialized: false,
cookie: { httpOnly: true, secure: true, sameSite: "lax", maxAge: 30 * 60 * 1000 },
}));
app.post("/login", async (req, res) => {
const user = await checkCredentials(req.body);
if (!user) return res.sendStatus(401);
req.session.userId = user.id; // stored on the server, not in the cookie
res.send("Logged in");
});
app.get("/me", (req, res) => res.json({ userId: req.session.userId }));Readers ask
What is the difference between a session and a cookie?
A cookie is a small piece of data stored in the browser and sent with requests, while a session is data stored on the server about a user's visit. In most setups the cookie only holds the session ID, which the server uses to find the session.
Should I use sessions or JWTs for authentication?
Server-side sessions are simple and can be revoked instantly by deleting them, which suits most traditional web apps. JWTs avoid a lookup on every request and can suit APIs shared by many services, but they are harder to revoke before they expire.
How long should a session last?
It depends on the risk. Banking apps often end sessions after a few minutes of inactivity, while low-risk apps may keep users signed in for weeks; a common pattern combines a short idle timeout with an absolute maximum lifetime.
Often compared
- Cookie vs SessionA cookie is small data the browser stores and sends back with each request, while a session is state the server keeps about a visitor, found by a cookie ID.
- JWT vs SessionA JWT is a signed token that carries the user's identity, so servers verify it without a lookup, while sessions keep state on the server behind a random ID.
See also
- CookieWeb Development, p. 6A cookie is a small piece of data a website asks the browser to store and send back with later requests, often used to keep users logged in.
- AuthenticationSecurity, p. 2Authentication is the process of verifying that a user, device, or service really is who it claims to be, for example by checking a password or passkey.
- JWTSecurity, p. 19A JWT is a compact, signed token that carries claims like a user ID and expiry time, letting a server verify requests without looking up a session.
- HTTPWeb Development, p. 19HTTP is the protocol that browsers, apps, and servers use to exchange web pages and data through a simple cycle of requests and responses.
- CacheBackend & APIs, p. 8A cache is a fast, temporary storage layer that keeps copies of frequently used data so later requests can be served quickly without repeating slow work.
- CSRFSecurity, p. 8CSRF is an attack that tricks a logged-in user's browser into sending an unwanted request to a trusted site, which treats it as a genuine user action.
- Session HijackingSecurity, p. 38Session hijacking is an attack in which someone steals or guesses a user's session ID or token and uses it to act as that user without knowing their password.
Spotted a mistake or something missing on this page?Suggest an edit