When you log in to a website, the website usually needs some way to remember that you are authenticated while you move from one page to another.
This is where cookies and sessions become important.
These concepts are fundamental to web development because HTTP itself is generally described as stateless. Without additional mechanisms, the server would not automatically remember that two separate requests came from the same authenticated user.
In this guide, you will learn what cookies are, what sessions are, how login systems use them, where data is stored, how cookies differ from sessions, session IDs, expiration, security attributes, PHP and JavaScript examples, common mistakes, and modern authentication considerations.
Why Do Websites Need Cookies and Sessions?
Consider a normal website login.
You enter your username and password and click Login.
The server verifies your credentials.
Now you visit another page.
How does the server know that you are still logged in?
HTTP requests are independent at the protocol level, so applications need additional mechanisms to associate requests with a user or client state.
Login Request
|
v
Authentication
|
v
Create Session
|
v
Session ID
|
v
Browser Cookie
|
v
Future Requests
|
v
Server Finds Session
|
v
User Recognized
What Is a Cookie?
A cookie is a small piece of data that a website can ask a browser to store.
The browser can then send the cookie back to the appropriate server with subsequent requests, subject to the cookie's attributes and browser rules.
A simplified example is:
Server | | Set-Cookie v Browser | | Cookie v Server
Cookies are commonly used for:
- Login sessions
- Preferences
- Shopping carts
- Language settings
- Analytics
- Security mechanisms
Example of a Cookie
A server may send a response header such as:
Set-Cookie: session_id=abc123
For later requests, the browser may send:
Cookie: session_id=abc123
The server can use the session identifier to locate associated server-side state.
What Is a Session?
A session is application state maintained across multiple requests from the same client.
In a common server-side session architecture, the server creates a session record containing information associated with the logged-in user.
For example:
Session ID: abc123
Server-side session:
{
userId: 101,
role: "user",
loggedIn: true
}
The browser usually stores only the session identifier rather than the complete session data.
Cookies vs Sessions
| Feature | Cookies | Server-Side Sessions |
|---|---|---|
| Typical storage | Browser | Server or shared session store |
| Data sent with requests | Applicable cookie data can be sent | Usually only a session identifier is sent by the client |
| Typical use | Preferences, identifiers, tracking, session IDs | Login state and server-maintained user state |
| Server control over data | Limited because data resides on client | Server controls session data |
| Security depends on | Cookie attributes, application design, transport security, and data stored | Session management, session IDs, storage security, authentication, and application design |
Cookie vs Session: The Most Important Idea
Cookies and sessions are not necessarily competing technologies.
They are often used together.
Browser | | Cookie: session_id=abc123 v Web Server | | Look up abc123 v Session Store | | userId=101 v Application
This is one of the most common patterns for browser-based authentication.
How Login Sessions Work
Let's look at a simplified login process.
Step 1: User Enters Credentials
POST /login
Step 2: Server Verifies Credentials
The server validates the submitted username and password against the application's authentication system.
Step 3: Server Creates a Session
The application creates a random session identifier and stores the associated server-side state.
Step 4: Server Sends Session Cookie
Set-Cookie: session_id=RANDOM_VALUE
Step 5: Browser Stores the Cookie
The browser stores the cookie according to the server's instructions and browser policies.
Step 6: Browser Sends the Cookie
Future applicable requests include the session cookie.
Step 7: Server Finds the Session
The server uses the session identifier to retrieve the associated session state.
Cookie ↓ Session ID ↓ Session Store ↓ User ID ↓ Authenticated Request
What Is a Session ID?
A session ID is an identifier used to associate a client with server-side session state.
It should be difficult for an attacker to guess.
A conceptual example is:
session_id = 9f5d8c7e3a1b...
Real session identifiers should be generated using secure randomness provided by the programming platform.
Why Should Session IDs Be Random?
If session identifiers are predictable, an attacker may be able to guess another user's session identifier and impersonate that user.
This type of attack is associated with session hijacking.
Applications should therefore use strong, unpredictable session identifiers and protect them during transport and storage.
What Is Session Hijacking?
Session hijacking is an attack in which an attacker obtains or abuses a valid user's session credentials or session identifier to act as that user.
Potential causes include:
- Stolen session cookies
- Insecure transport
- Cross-site scripting
- Malware
- Compromised devices
- Session management flaws
Applications should protect session identifiers as carefully as authentication credentials.
What Is the Secure Cookie Attribute?
The Secure cookie attribute tells compatible browsers to send the cookie only over secure connections, typically HTTPS.
Set-Cookie: session_id=abc123; Secure
For authentication cookies, Secure is an important security control.
What Is the HttpOnly Attribute?
The HttpOnly attribute prevents browser-side JavaScript from directly accessing the cookie through APIs such as document.cookie.
Set-Cookie: session_id=abc123; HttpOnly
This can reduce the risk of certain cookie theft scenarios involving client-side scripts.
However, HttpOnly does not prevent cross-site scripting itself and does not make an application immune to XSS attacks.
What Is SameSite?
SameSite is a cookie attribute that controls when browsers send cookies in cross-site contexts.
Common settings include:
- Strict
- Lax
- None
The appropriate setting depends on the application architecture and cross-site requirements.
When SameSite=None is used, browsers require the cookie to also have the Secure attribute.
Secure Session Cookie Example
A typical session cookie might be configured conceptually like:
Set-Cookie: session_id=RANDOM_VALUE; Secure; HttpOnly; SameSite=Lax
The exact settings should match the application's architecture and authentication flow.
What Is a Session Expiration?
Sessions should generally have a defined lifetime or inactivity policy.
For example, an application can expire a session after a period of inactivity.
Login ↓ Session Created ↓ User Active ↓ Session Valid ↓ Inactivity ↓ Session Expires ↓ Login Required
Session lifetime should be appropriate to the sensitivity of the application.
Cookie Expiration
Cookies can also have expiration behavior.
A cookie without a persistent expiration can behave as a session cookie, while cookies with an expiration or max-age can persist longer according to browser rules.
For example:
Set-Cookie: preference=dark; Max-Age=3600
This example requests a one-hour lifetime.
Session Cookie vs Persistent Cookie
| Session Cookie | Persistent Cookie |
|---|---|
| Generally intended to last for a browser session | Has an expiration or Max-Age |
| Often used for temporary state | Can persist across browser restarts according to browser rules |
Where Are Cookies Stored?
Cookies are stored by the browser according to its internal storage system and policies.
Developers can inspect cookies through browser developer tools.
You may see fields such as:
- Name
- Value
- Domain
- Path
- Expires
- Secure
- HttpOnly
- SameSite
Where Are Server-Side Sessions Stored?
Session storage depends on the application.
A session can be stored in:
- Server memory
- Files
- Databases
- Redis
- Other shared session stores
For scalable applications running across multiple servers, shared session storage or another architecture that avoids server-local session dependency may be required.
Cookies vs Sessions in PHP
PHP provides built-in session functionality.
A basic example is:
<?php session_start(); $_SESSION["user_id"] = 101; echo $_SESSION["user_id"]; ?>
PHP can use a session cookie to associate the browser with server-side session data.
PHP Cookie Example
You can also create a cookie directly:
<?php
setcookie(
"theme",
"dark",
[
"expires" => time() + 3600,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]
);
?>
Cookie configuration should match the application's deployment and cross-site requirements.
JavaScript Cookies
JavaScript can read cookies that are not marked HttpOnly through document.cookie.
console.log(document.cookie);
Cookies marked HttpOnly are intentionally unavailable to client-side JavaScript.
Client-Side Cookies vs Server-Side Sessions
CLIENT-SIDE COOKIE Browser | +-- Stores data | +-- Sends applicable cookie SERVER-SIDE SESSION Browser | +-- Stores Session ID | v Server | +-- Stores Session Data
This difference is important because sensitive application state generally should not simply be trusted because it is stored in a browser cookie.
Can Cookies Store Sensitive Information?
Cookies can contain sensitive information, but developers should think carefully before putting sensitive data directly into client-side storage.
Cookies are sent with applicable requests and can contribute to request size.
Authentication cookies should be configured securely.
For sensitive application state, many applications store only an identifier in the cookie and keep the actual session state server-side.
Can a Cookie Be Modified by the User?
Yes. Data stored on the client should generally be treated as untrusted unless it is protected by an appropriate integrity mechanism and the server validates it.
For example, if a cookie says:
role=admin
the server should not simply assume that the user is an administrator.
Authorization must be enforced server-side.
What Is Cookie Tampering?
Cookie tampering means modifying cookie data in an attempt to change application behavior.
Applications should never trust client-controlled values for sensitive authorization decisions without appropriate cryptographic protection and server-side validation.
Cookies and Authentication
Browser-based authentication often uses a secure session cookie.
The flow can look like:
Login ↓ Credentials Verified ↓ Session Created ↓ Session ID Stored in Cookie ↓ Browser Sends Cookie ↓ Server Retrieves Session ↓ User Authenticated
This architecture is common because the browser does not need to store the complete server-side session state.
What Is Session Fixation?
Session fixation is an attack in which an attacker causes or predicts a session identifier before the victim authenticates and then attempts to benefit after authentication occurs.
A major defense is to regenerate the session identifier after a successful login or privilege change.
Session Regeneration
After authentication, applications should use a new session identifier rather than continuing to use an identifier that existed before authentication.
In PHP, a common mechanism is:
<?php session_start(); session_regenerate_id(true); $_SESSION["user_id"] = 101; ?>
This is a simplified example; complete authentication systems need additional security controls.
What Is Session Logout?
Logging out should invalidate the authenticated session according to the application's session management design.
Conceptually:
Logout ↓ Invalidate Session ↓ Delete / Expire Cookie ↓ Future Requests ↓ Authentication Required
Simply removing a visual login state in the browser is not enough. The server should invalidate the session or authentication credential as appropriate.
Cookies and HTTPS
Authentication cookies should generally be transmitted over HTTPS.
The Secure attribute helps ensure the cookie is sent only through secure connections.
Secure Cookie
|
v
HTTPS
|
v
Server
HTTPS also helps protect the broader communication channel between browser and server.
What Is a Third-Party Cookie?
A third-party cookie is traditionally a cookie associated with a domain different from the site the user is directly visiting, typically arising from embedded third-party content or services.
Browser policies regarding third-party cookies have changed significantly over time and differ by browser and privacy settings.
Developers should therefore check current browser behavior when implementing cross-site functionality.
First-Party vs Third-Party Cookies
| First-Party Cookie | Third-Party Cookie |
|---|---|
| Associated with the site the user is visiting | Associated with another domain in a cross-site context |
| Often used for login and preferences | Historically used for advertising, analytics, and embedded services |
What Is a Cookie Domain?
The Domain attribute determines which hosts can receive a cookie according to browser cookie rules.
For example:
Set-Cookie: theme=dark; Domain=example.com
Cookie domain behavior can be subtle, so developers should understand the current browser rules before sharing cookies across subdomains.
What Is the Cookie Path?
The Path attribute controls the URL path scope in which the browser sends the cookie.
For example:
Set-Cookie: session_id=abc123; Path=/
Using / means the cookie is available across paths on the relevant host according to cookie rules.
Cookies and CSRF
Cookie-based authentication requires developers to consider Cross-Site Request Forgery (CSRF).
Because browsers can automatically attach cookies to applicable requests, a malicious website may attempt to cause a user's browser to send an authenticated request to another website.
Defenses can include:
- SameSite cookie configuration
- CSRF tokens
- Origin or Referer checks where appropriate
- Appropriate request design
Cookies and XSS
Cross-Site Scripting (XSS) can allow malicious scripts to execute in a user's browser.
An HttpOnly authentication cookie cannot be directly read by JavaScript, which can reduce one type of cookie theft.
However, XSS can still be extremely serious because malicious code may perform actions through the user's authenticated browser session.
Therefore:
Session Storage vs Local Storage
Web developers often confuse browser cookies with localStorage and sessionStorage.
| Storage | Main Characteristic |
|---|---|
| Cookie | Can be automatically sent with matching HTTP requests |
| localStorage | Client-side storage accessible to same-origin JavaScript |
| sessionStorage | Client-side storage associated with a particular browser tab/session context |
These mechanisms have different security and persistence characteristics.
Cookie vs localStorage for Authentication
There is no universal answer for every application, but the choice should be based on the application's threat model and architecture.
Authentication cookies can use security attributes such as HttpOnly, Secure, and SameSite.
Data in localStorage is accessible to JavaScript running in the page's origin. This can make sensitive token storage particularly important to evaluate in applications where XSS is a concern.
Sessions in Load-Balanced Applications
Imagine your website runs on three application servers.
Load Balancer
/ | \
v v v
Server1 Server2 Server3
If session data exists only in Server 1's local memory, a later request routed to Server 2 may not find the session.
Common solutions include:
- Shared session storage
- Redis-backed sessions
- Database-backed sessions
- Other distributed session architectures
- Stateless authentication designs where appropriate
Sessions and Redis
Redis is frequently used as a fast shared data store for session information.
Browser
|
Cookie: session_id=abc123
|
v
Load Balancer
|
+---- Server 1
|
+---- Server 2
|
+---- Server 3
|
v
Redis
|
v
Session Data
This allows multiple application servers to access the same session state when designed appropriately.
Cookie Size and Request Overhead
Cookies are sent with applicable HTTP requests, so putting large amounts of data into cookies increases request overhead.
For this reason, cookies are usually kept relatively small.
Large application data should generally be stored elsewhere, such as server-side storage, databases, or suitable client-side storage mechanisms.
Cookies vs Sessions for Shopping Carts
Shopping carts can use cookies, sessions, databases, or combinations of these technologies.
A simple cart might store a session identifier in a cookie and the actual cart state on the server.
Browser
Cookie:
cart_session=abc123
|
v
Server
|
v
Cart Data
|
+-- Product A
+-- Product B
This approach can keep important business data under server-side control.
Cookies vs Sessions for User Preferences
Simple preferences such as language or a display preference may sometimes be stored directly in a cookie.
For example:
language=en theme=dark
Whether the preference should be stored in a cookie, account profile, or another location depends on the application's requirements.
Cookies vs Sessions in APIs
APIs can use cookie-based sessions, token-based authentication, or other authentication mechanisms.
For a traditional browser application:
Browser | Cookie | v Web API | Session Store
For other API clients, bearer tokens or other credentials may be used instead.
Session Authentication vs JWT
Server-side sessions and JWT-based authentication are different approaches.
| Server-Side Session | JWT-Based Authentication |
|---|---|
| Server maintains session state | Token contains claims and is verified by the application |
| Client commonly stores a session ID | Client stores the token according to application design |
| Server can invalidate a session centrally | Revocation requires additional design when tokens are independently valid until expiration |
| Requires session-state infrastructure for multiple servers | Can reduce dependence on centralized request state, depending on the architecture |
JWTs are not automatically better than sessions. The correct authentication design depends on the application's requirements and threat model.
Common Cookie Security Mistakes
- Not using HTTPS for authentication.
- Failing to use Secure for sensitive cookies.
- Failing to use HttpOnly where client-side access is unnecessary.
- Ignoring SameSite configuration.
- Putting sensitive authorization decisions entirely inside client-controlled cookie data.
- Using predictable session identifiers.
- Failing to regenerate sessions after authentication.
- Not expiring or invalidating sessions appropriately.
Common Session Security Mistakes
- Using weak session IDs.
- Keeping sessions alive indefinitely.
- Not invalidating sessions after logout.
- Not regenerating session IDs after login.
- Storing session data insecurely.
- Allowing session IDs to travel over unencrypted connections.
- Failing to protect against XSS and CSRF.
Best Practices for Secure Sessions
- Use HTTPS.
- Generate unpredictable session identifiers.
- Use Secure cookies for sensitive sessions.
- Use HttpOnly for authentication cookies when JavaScript does not need access.
- Configure SameSite appropriately.
- Regenerate the session ID after authentication or privilege changes.
- Expire idle sessions appropriately.
- Invalidate sessions on logout and account-security events.
- Protect against XSS and CSRF.
- Monitor suspicious authentication activity.
Cookies vs Sessions: Easy Memory Trick
Cookie = Client-side storage
Session = Server-side state
Common login pattern = Session ID in a secure cookie + session data on the server
Frequently Asked Questions
What is the difference between cookies and sessions?
Cookies are browser-stored data that can be sent with applicable requests, while server-side sessions store application state on the server and commonly use a session ID stored in a cookie to identify that state.
Are cookies stored on the client?
Yes. Cookies are stored by the browser on the client device according to browser policies and cookie attributes.
Are sessions stored on the server?
In the common server-side session model, yes. Session state is stored on a server or shared session store.
Can cookies and sessions be used together?
Yes. A common authentication architecture stores a session identifier in a browser cookie while the associated session data remains server-side.
What is a session ID?
A session ID is an identifier that lets the server associate a request with server-side session state.
What is HttpOnly?
HttpOnly prevents client-side JavaScript from directly accessing a cookie.
What is Secure in a cookie?
The Secure attribute tells compatible browsers to send the cookie only over secure connections such as HTTPS.
What is SameSite?
SameSite controls when a browser sends a cookie in cross-site contexts.
Can a user modify cookies?
Yes. Client-side data should be treated as potentially untrusted. Sensitive authorization decisions must be enforced on the server.
What is session hijacking?
Session hijacking occurs when an attacker obtains or abuses a valid session credential or identifier to act as another user.
What is session fixation?
Session fixation is an attack in which an attacker attempts to make a victim use a session identifier known to the attacker before authentication.
Why regenerate a session ID after login?
Regenerating the session identifier after authentication helps defend against session fixation.
What happens when a user logs out?
A secure application should invalidate the authenticated session or credential and remove or expire the corresponding client-side credential as appropriate.
Are sessions more secure than cookies?
Cookies and sessions are different mechanisms and are often used together. Security depends on implementation, session management, cookie attributes, authentication design, transport security, and application security.
What is the difference between cookies and localStorage?
Cookies can be automatically sent with applicable HTTP requests, while localStorage is client-side storage accessible to same-origin JavaScript and is not automatically included in HTTP requests.
```Final Thoughts
Cookies and sessions are foundational concepts in web development.
The easiest way to understand their relationship is:
LOGIN
↓
Authentication
↓
Create Session
↓
+----------------------+
| Server |
| Session Data |
| userId = 101 |
+----------------------+
↑
|
Session ID
|
↓
+----------------------+
| Browser Cookie |
+----------------------+
|
↓
Future Requests
The browser carries the session identifier, while the server uses that identifier to retrieve the associated state.
For developers, the most important security lessons are use HTTPS, protect session identifiers, use appropriate cookie attributes, regenerate sessions after login, enforce authorization server-side, expire sessions appropriately, and protect the application against XSS and CSRF.
Never assume that a value stored in the browser is trustworthy. The browser is controlled by the user, so authentication and authorization decisions must ultimately be enforced by the server.
Related Articles on CodeWithAV
HTTP Status Codes Every Developer Should Know
What Is an API? Complete Beginner Guide
REST API Explained With Examples
Explore More Web Development and Cybersecurity Guides
CodeWithAV — Learn, Discover & Build.