
If you are interviewing for a web developer role, someone will probably ask you this. Most people answer "cookies are stored in the browser, sessions are stored on the server" and stop there. That is right, but it is only half the answer. Sessions and cookies are not really rivals. In most websites they work together, and interviewers like it when you can explain how.
So let's go through what each one is, how a login actually works with both, and when you would pick one over the other.
The short answer
A cookie is a small piece of text that a server asks your browser to save. After that, the browser sends it back to the same site with every request.
A session is information the server keeps about you, on the server. To know which session belongs to which visitor, the server gives your browser a long random session ID. And where does the browser keep that ID? Usually in a cookie.
So the actual session data stays on the server. Your browser only holds the key that points to it.
What is a cookie?
When a server sends a response, it can include a Set-Cookie header. The browser saves that value and automatically attaches it, in a Cookie header, to later requests for the same site.
Set-Cookie: theme=dark; Max-Age=31536000; Path=/
A few things worth knowing:
- Each cookie is a name and a value, and is limited to about 4 KB.
- If you set
ExpiresorMax-Age, the cookie survives browser restarts. If you don't, it is a "session cookie" and the browser removes it when it closes. - Cookies are scoped to a domain and path, so one site cannot read another site's cookies.
- They travel with every matching request, so large or numerous cookies slow things down a little.
The big catch: a cookie lives on the user's machine, so the user can see it and change it in DevTools. Never store something like role=admin or a price in a plain cookie and trust it later.
Typical uses are remembering a language or dark mode, "remember me" options, analytics IDs, and of course holding the session ID.
What is a session?
A session is a small record the server stores for each visitor, for example { userId: 42, cart: [3 items] }. It can live in server memory, in files, in a database or in a fast store like Redis. Every backend has its own version: $_SESSION in PHP, HttpSession in Java, express-session in Node.js.
Because the data never leaves the server, the user cannot read or edit it. They only ever see the random ID.
How a login actually works
This is the part that ties it all together, and it is a great thing to walk through in an interview:
- You submit your email and password.
- The server checks them, creates a session record for you and generates a long, random session ID.
- The response includes something like
Set-Cookie: sid=8f3a...; HttpOnly; Secure; SameSite=Lax. - Your browser now sends that cookie with every request.
- For each request, the server looks up the ID, finds your session and knows who you are.
- When you log out, the server deletes the session record. Even if someone had copied the old ID, it is now useless.
That last step is a real advantage of sessions: the server can end them instantly, whenever it wants.
Sessions vs cookies: side by side
| Point | Cookie | Session |
|---|---|---|
| Where the data lives | In the browser | On the server (memory, files, Redis, database) |
| Size | About 4 KB per cookie | Limited only by server storage |
| How long it lasts | Until it expires, or until the browser closes | Until logout or a server-side timeout |
| Who can read or change it | The user (and JavaScript, unless HttpOnly) | Only the server |
| Good for sensitive data? | No | Yes, as long as the session ID is protected |
| Cost | Extra bytes on every request | Server memory or storage, and a shared store when you have many servers |
| Common uses | Preferences, tracking, holding the session ID | Login state, shopping carts, multi-step forms |
When to use which
Use a session when the data matters or should not be tampered with: who is logged in, their role, cart contents, progress through a checkout or a long form.
Use a plain cookie when the data is small, harmless if the user sees or changes it, and you want it to stick around: theme, language, a dismissed banner.
A simple rule I use: if a user editing the value could cause a problem, keep it on the server.
Cookie security flags you should mention
If you only remember one extra thing for the interview, make it these flags. They are what make a session cookie safe:
- HttpOnly: JavaScript cannot read the cookie through
document.cookie. This stops an XSS attack from simply stealing the session ID. - Secure: the cookie is only sent over HTTPS, never plain HTTP.
- SameSite: controls whether the cookie is sent on requests coming from other sites.
Lax(the default in modern browsers) orStrictis your main protection against CSRF. - Short expiry: auth cookies should not live for months unless the user chose "remember me".
One more good point to add: generate a fresh session ID right after login. That prevents session fixation, where an attacker tricks you into using an ID they already know. If you want the full picture, read Learn Frontend: Web Security (XSS, CSRF, CORS and secure token storage).
Where do JWTs and localStorage fit in?
Interviewers often follow up with this, so it helps to be ready.
- JWT (JSON Web Token): instead of storing a session, the server signs a token with the user's details and the client sends it back. The server does not need to store anything, which is handy across many servers, but a token is hard to cancel before it expires. Sessions are "stateful", JWTs are mostly "stateless".
- localStorage: holds around 5 MB per site, is never sent automatically and can only be read by JavaScript. That last part is the risk: any script running on the page, including one injected through XSS, can read it. That is why many teams keep auth tokens in an HttpOnly cookie instead.
Quick revision
- Cookies are stored in the browser and sent with every request to that site.
- Session data is stored on the server; the browser only keeps a session ID, usually in a cookie.
- Cookies are small (about 4 KB) and can be seen and edited by the user.
- Keep anything sensitive or important in the session, not in a plain cookie.
- Protect session cookies with HttpOnly, Secure and SameSite.
- Logging out should destroy the session on the server, not just delete the cookie.
Frequently asked questions
Is a session stored inside a cookie?
Usually not. Normally only the session ID is in the cookie and the data stays on the server. Some frameworks do offer "cookie sessions", where the whole session is signed or encrypted and stored in the cookie itself. They save server storage, but they are still limited to about 4 KB and are harder to revoke.
What happens to my session when I close the browser?
If the session cookie had no expiry, the browser deletes it, so you lose the ID and are effectively logged out. The data on the server stays until its timeout cleans it up.
Are sessions more secure than cookies?
The data is safer because users cannot see or edit it. But the whole thing is only as safe as the session ID, so it still needs HTTPS, HttpOnly, SameSite and a proper logout.
How do sessions work when a site runs on many servers?
Either every server reads sessions from a shared store like Redis or a database, or a load balancer uses "sticky sessions" to send each user back to the same server. A shared store is the more common and more reliable option.
New to how browsers and servers talk to each other? Start with How the Web Works: DNS, HTTP, HTTPS, caching and APIs, or browse more questions in the Interview Questions Hub.
Comments
Post a Comment