What Is Two-Factor Authentication (2FA)? Complete Beginner Guide

Passwords are one of the most common ways people protect online accounts. But a password can be stolen, guessed, reused, leaked, or obtained through phishing.

For this reason, many online services offer an additional security layer called Two-Factor Authentication, commonly abbreviated as 2FA.

With 2FA enabled, knowing the password alone is not normally enough to complete authentication. The user must provide another authentication factor.

Simple Definition: Two-factor authentication is an authentication method that requires two different types of authentication factors before access is granted.

In this guide, you will learn what 2FA means, how it works, authentication factors, OTP apps, SMS codes, security keys, passkeys, backup codes, recovery methods, phishing risks, common mistakes, and how to enable 2FA on your accounts.

What Does 2FA Stand For?

2FA stands for Two-Factor Authentication.

Authentication means proving that you are the person or entity associated with an account or identity.

With traditional password authentication:

Username + Password
        ↓
     Account
  

With 2FA:

Password
   +
Second Factor
   ↓
Authentication
   ↓
Account Access
  

Why Is 2FA Important?

Imagine someone discovers your password.

Without an additional authentication factor, the attacker may be able to sign in.

With 2FA enabled, the attacker may still need a second factor.

Attacker knows password
          |
          v
      Login Attempt
          |
          v
     Second Factor?
          |
          X
     Access Denied
  

This creates an additional barrier against many account-compromise scenarios.

What Are Authentication Factors?

Authentication factors are commonly grouped into categories based on what the user knows, has, or is.

1. Something You Know

This is information that should be known by the user.

Examples include:

  • Password
  • PIN
  • Passphrase

2. Something You Have

This refers to a physical or digital authenticator controlled by the user.

Examples include:

  • Security key
  • Authenticator application
  • Registered phone
  • Hardware token

3. Something You Are

This refers to biometric characteristics.

Examples include:

  • Fingerprint
  • Face recognition
  • Other biometric characteristics

Two-Factor vs Two-Step Verification

The terms two-factor authentication and two-step verification are sometimes used interchangeably, but they are not necessarily identical concepts.

Two-factor authentication specifically involves two different authentication factors.

Two-step verification means authentication happens in two steps, but the two steps do not necessarily represent two different factor categories.

For example:

Password
   +
One-Time Code
   =
Two Different Factors
  

is a typical 2FA arrangement.

How Does 2FA Work?

A simplified login process looks like this:

Step 1
Enter username
      ↓
Step 2
Enter password
      ↓
Step 3
Server verifies password
      ↓
Step 4
Second factor requested
      ↓
Step 5
User provides second factor
      ↓
Step 6
Server verifies factor
      ↓
Step 7
Access granted
  

The exact process varies depending on the authentication technology.

Example of 2FA Login

Suppose you sign in to an account.

First you enter:

Username: adarsh
Password: ********
  

The service then requests a code:

Enter your 6-digit verification code
  

Your authenticator application displays something like:

482913
  

After successfully verifying the code, the service completes authentication.

What Is an OTP?

OTP stands for One-Time Password.

An OTP is a temporary authentication code designed to be used for a limited period or authentication event.

Examples can include codes delivered through:

  • Authenticator applications
  • SMS
  • Email in some systems
  • Hardware tokens

Different OTP technologies have different security properties.

What Is TOTP?

TOTP stands for Time-Based One-Time Password.

TOTP applications generate temporary codes based on a shared secret and the current time.

A simplified concept is:

Shared Secret
      +
Current Time
      ↓
TOTP Algorithm
      ↓
Temporary Code
  

Popular authenticator applications can generate TOTP codes without receiving the code through SMS for every login.

What Is HOTP?

HOTP stands for HMAC-Based One-Time Password.

Unlike TOTP, HOTP is based on a counter rather than time.

Shared Secret
      +
Counter
      ↓
HOTP
      ↓
One-Time Code
  

TOTP and HOTP are standardized approaches for generating one-time passwords.

Authenticator App 2FA

An authenticator application can generate verification codes directly on a trusted device.

A typical setup works like this:

  1. Open account security settings.
  2. Choose authenticator-based authentication.
  3. Scan a QR code or enter a setup key.
  4. The app stores the shared secret.
  5. The app generates temporary codes.
  6. Enter a generated code to verify setup.

After setup, the app can generate codes during login.

What Is SMS-Based 2FA?

With SMS-based authentication, the service sends a temporary code to a registered phone number.

Login
  ↓
Password Verified
  ↓
SMS Code Sent
  ↓
Phone
  ↓
Enter Code
  ↓
Access
  

SMS can provide additional protection compared with password-only authentication, but it has known weaknesses and is generally not considered as resistant to phishing and account-takeover attacks as phishing-resistant authentication methods.

What Is SIM Swapping?

SIM swapping is an attack in which an attacker fraudulently convinces a mobile carrier or related system to transfer a victim's phone number to a SIM or eSIM controlled by the attacker.

If an account relies on SMS verification, successful control of the phone number can potentially allow an attacker to receive verification codes.

This is one reason security-conscious users may prefer stronger authentication methods where available.

What Is a Security Key?

A security key is a physical authentication device designed to prove possession of a cryptographic credential.

Modern security keys can support standards such as FIDO2/WebAuthn.

A simplified login looks like:

Username + Password
        ↓
Security Key
        ↓
Cryptographic Verification
        ↓
Access
  

Security keys can provide strong protection against credential phishing because the authentication ceremony is bound to the website origin.

What Is Phishing-Resistant Authentication?

Phishing-resistant authentication is designed to prevent attackers from simply tricking users into giving them a reusable authentication secret through a fake website.

FIDO-based authentication is an important example of this approach.

Instead of asking the user to type a reusable code into a website, a cryptographic challenge-response mechanism can authenticate the user's registered authenticator.

What Are Passkeys?

Passkeys are credentials based on public-key cryptography and built on standards from the FIDO ecosystem.

A passkey allows a user to authenticate using an authenticator such as a device, security key, or platform credential.

Instead of sending a reusable password to the website, the authentication system uses public-key cryptography to prove possession of the corresponding private key.

Website
   |
   | Challenge
   v
Authenticator
   |
   | Cryptographic Response
   v
Website
   |
   v
Authentication
  

Passkeys can provide strong phishing resistance when implemented according to the relevant standards and platform behavior.

Is a Passkey the Same as a Password?

No.

A password is generally a shared secret that the user types.

A passkey uses public-key cryptography and an authenticator to prove possession of a private credential.

2FA Methods Comparison

Method Example Important Consideration
SMS OTP 6-digit SMS code Can be exposed through phone-number attacks such as SIM swapping
Authenticator App TOTP code Requires protection and backup of the authenticator setup
Security Key FIDO2 hardware key Strong phishing resistance; requires possession of the key
Passkey Device-based FIDO credential Uses public-key cryptography and depends on supported devices/platforms
Biometric Factor Fingerprint or face recognition Often used to unlock an authenticator rather than sent directly as a password

Does 2FA Guarantee Account Security?

No.

2FA significantly improves account security, but it does not eliminate every attack.

Accounts can still be compromised through:

  • Phishing
  • Malware
  • Session theft
  • Account-recovery attacks
  • Compromised devices
  • Social engineering
  • Weak recovery methods
  • Application vulnerabilities

The strength of the second factor also matters.

Can Attackers Bypass 2FA?

Attackers may attempt to bypass authentication controls through different techniques.

Examples include:

  • Phishing pages that request the OTP
  • Social engineering
  • Session-cookie theft
  • Compromised recovery channels
  • SIM swapping for SMS-based authentication

This is why phishing-resistant authentication methods can provide valuable additional protection.

What Is an Adversary-in-the-Middle Attack?

An attacker may create a fake login flow that sits between the user and the legitimate authentication service.

The attacker attempts to capture credentials or session information during the authentication process.

Traditional password and OTP systems can sometimes be targeted by these techniques.

Phishing-resistant technologies such as WebAuthn are designed to bind authentication to the legitimate origin, making many such attacks more difficult.

What Are Backup Codes?

Backup codes are one-time recovery codes provided by some services when you enable 2FA.

They are intended for situations such as losing access to your normal authentication device.

Example:

A1B2-C3D4
E5F6-G7H8
I9J0-K1L2
M3N4-O5P6
  

These are only example formats. Real backup codes should be unique to your account and stored securely.

How Should You Store Backup Codes?

Backup codes should be protected like sensitive recovery credentials.

Possible approaches include:

  • Secure password manager
  • Offline secure storage
  • Another protected recovery mechanism

Do not publish backup codes in screenshots, public repositories, chats, or social media.

What Happens If You Lose Your Phone?

The answer depends on the authentication method.

Possible recovery options include:

  • Backup codes
  • Registered security keys
  • Additional authentication devices
  • Account recovery procedures
  • Recovery codes or trusted contacts where supported

This is why setting up a recovery method when enabling 2FA is important.

Should You Register More Than One Security Key?

For accounts that support hardware security keys, registering more than one key can provide a backup in case the primary key is lost or damaged.

Store backup authenticators securely and separately.

What Is Step-Up Authentication?

Step-up authentication means requiring stronger authentication when a user performs a sensitive action.

For example:

Normal Account Access
       ↓
Password / Existing Session
       ↓
Sensitive Operation
       ↓
Additional Authentication
       ↓
Action Allowed
  

This can be used for operations such as changing security settings, adding payment information, or changing account recovery methods.

2FA vs MFA

MFA stands for Multi-Factor Authentication.

MFA means using multiple authentication factors.

2FA is a specific case of MFA that uses exactly two factors.

MFA
 |
 +-- 2 factors → 2FA
 |
 +-- 3 or more factors
  

What Is Passwordless Authentication?

Passwordless authentication allows a user to authenticate without entering a traditional password.

Passkeys are one example of a passwordless authentication technology.

Passwordless authentication and 2FA are related but not identical concepts.

Does Passwordless Mean No Security?

No.

Passwordless authentication can use strong cryptographic authentication mechanisms.

For example:

Device
  |
Authenticator
  |
Public-Key Cryptography
  |
Website
  |
Authentication
  

The security model is different from password-based authentication.

2FA for Email Accounts

Email accounts are especially important because they are often connected to password resets for other services.

Protecting an email account can therefore help reduce the impact of credential compromise elsewhere.

Useful security measures include:

  • Strong unique password
  • 2FA or stronger authentication
  • Secure recovery options
  • Login alerts
  • Account activity monitoring
  • Recovery codes stored securely

2FA for Social Media Accounts

Social media accounts can contain personal information, messages, content, and connections.

Users should enable available strong authentication options and review:

  • Active sessions
  • Recovery email
  • Recovery phone
  • Connected applications
  • Login alerts

2FA for GitHub and Developer Accounts

Developer accounts can provide access to source code, deployment systems, cloud environments, package repositories, and infrastructure.

Protecting them with strong authentication is particularly important.

Developers should also:

  • Use unique passwords
  • Enable strong MFA methods
  • Protect recovery codes
  • Review active sessions
  • Remove unused access tokens
  • Protect SSH keys
  • Review connected applications

2FA for Cloud Accounts

Cloud accounts can control servers, databases, storage, networks, secrets, and other infrastructure.

A compromised cloud administrator account can have significant consequences.

Organizations should use strong authentication and least-privilege access controls for cloud identities.

2FA and API Security

Human login authentication and machine-to-machine API authentication are different problems.

2FA normally applies to a human authentication flow rather than being added directly to every API request.

APIs may instead use:

  • Access tokens
  • API keys
  • OAuth flows
  • Signed requests
  • Other machine authentication mechanisms

2FA and Session Security

Successfully completing 2FA does not mean that the account remains secure forever.

After authentication, the application usually creates an authenticated session or credential.

Password
   +
2FA
   ↓
Authenticated
   ↓
Session
   ↓
Authenticated Requests
  

If an attacker steals a valid session credential, they may be able to access the account without repeating the login process.

This is why session security is also important.

2FA and Device Security

Your second factor is only as secure as the device or authenticator protecting it.

Keep devices secure by:

  • Installing updates
  • Using a screen lock
  • Installing applications from trusted sources
  • Using device encryption where appropriate
  • Avoiding suspicious software

Common 2FA Mistakes

  1. Using the same password everywhere.
  2. Sharing verification codes with other people.
  3. Approving unexpected login prompts.
  4. Storing backup codes publicly.
  5. Using only SMS when stronger options are available for sensitive accounts.
  6. Failing to configure recovery methods.
  7. Ignoring account-login alerts.
  8. Leaving old authenticators registered.

Never Share a 2FA Code

A genuine support representative should not need you to disclose a one-time authentication code for your account.

Attackers sometimes impersonate support staff and ask for OTPs.

Security Rule: Treat one-time authentication codes as secrets. Never share a login code with someone who contacts you by phone, email, chat, or social media.

How to Enable 2FA

The exact instructions vary by service, but the general process is:

  1. Open your account security settings.
  2. Find the two-factor or multi-factor authentication section.
  3. Choose an available authentication method.
  4. Complete the setup process.
  5. Verify the factor.
  6. Save recovery codes securely.
  7. Register a backup authentication method where appropriate.

Which 2FA Method Should You Use?

The best available method depends on the service and your threat model.

For sensitive accounts, prioritize authentication methods that provide strong phishing resistance where the service supports them.

Authenticator applications can provide a practical alternative when security keys or passkeys are not available.

SMS-based authentication can still provide an additional security layer, but it has weaknesses that users should understand.

2FA Security Hierarchy

There is no universal ranking for every situation, but the following model helps explain the major differences:

Password Only
     ↓
Password + SMS OTP
     ↓
Password + Authenticator App
     ↓
Password + Security Key
     ↓
Phishing-Resistant Authentication
     ↓
Modern Passwordless / Passkey Authentication
  

This diagram is conceptual rather than a universal ranking. The exact security outcome depends on implementation, account recovery, device security, and the attack scenario.

Frequently Asked Questions

```

What is two-factor authentication?

Two-factor authentication is an authentication method that requires two different authentication factors before access is granted.

What does 2FA stand for?

2FA stands for Two-Factor Authentication.

What are the three common authentication factors?

They are commonly described as something you know, something you have, and something you are.

Is a password plus OTP 2FA?

Yes, when the password and OTP represent two different authentication factors, such as a password plus a possession-based authenticator.

Is SMS 2FA secure?

SMS adds protection compared with password-only authentication, but it has weaknesses such as SIM-swapping and phishing risks. Stronger authentication methods may be preferable for sensitive accounts when available.

What is an authenticator app?

An authenticator app is an application that can generate temporary authentication codes, commonly using TOTP.

What is TOTP?

TOTP stands for Time-Based One-Time Password. It generates temporary codes using a shared secret and current time.

What is a security key?

A security key is a physical authenticator that can use cryptographic protocols such as FIDO2/WebAuthn to authenticate a user.

What are passkeys?

Passkeys are public-key-based credentials from the FIDO ecosystem that can provide passwordless and phishing-resistant authentication.

Can hackers bypass 2FA?

Attackers can attempt phishing, session theft, social engineering, recovery attacks, and other techniques. The effectiveness of 2FA depends on the authentication method and the rest of the account-security architecture.

Should I enable 2FA on Gmail?

Enabling strong additional authentication on important accounts such as email can reduce the risk associated with stolen passwords.

What are backup codes?

Backup codes are one-time recovery credentials provided by some services for situations where the normal second factor is unavailable.

What happens if I lose my phone?

Recovery depends on the service. Backup codes, a second registered device, a security key, or the provider's account-recovery process may provide alternatives.

Is 2FA the same as MFA?

2FA is a type of MFA that specifically uses two authentication factors. MFA is the broader concept of using multiple factors.

Does 2FA stop phishing?

Not all forms of 2FA stop phishing. Some methods, especially one-time codes, can be tricked through real-time phishing. Phishing-resistant methods such as WebAuthn are designed to provide stronger resistance.

Does 2FA make an account unhackable?

No. 2FA adds an important security layer but does not make an account completely immune to compromise.

```

Final Thoughts

Two-factor authentication is one of the most useful security controls available for protecting online accounts.

The core idea is simple:

Something You Know
        +
Something You Have
        ↓
     2FA

or

Something You Know
        +
Something You Are
        ↓
     2FA
  

However, not all second factors provide the same protection.

SMS codes can add protection but have known weaknesses. Authenticator applications can provide stronger protection against some attacks. Security keys and passkey-based authentication use public-key cryptography and can offer strong resistance to phishing when correctly implemented.

For your most important accounts, use the strongest authentication method supported by the service, protect recovery credentials, secure your devices, and never share verification codes.

CodeWithAV Security Checklist:

Use a unique password → Enable 2FA/MFA → Prefer phishing-resistant authentication when available → Store backup codes securely → Review active sessions → Secure your recovery options → Never share OTPs.

Related Articles on CodeWithAV

Cookies vs Sessions: Complete Beginner Guide

HTTP vs HTTPS Explained

Public IP vs Private IP

IPv4 vs IPv6 Explained

What Is a VPN?

Explore More Cybersecurity Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.

Cookies vs Sessions: What Is the Difference? Complete Beginner Guide

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.

Simple Definition: A cookie is data stored by the browser and sent with applicable requests, while a session is commonly server-side state associated with a client through a session identifier, often stored in a cookie.

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:

Important: HttpOnly helps protect the cookie from direct JavaScript access, but it does not eliminate the need to prevent XSS.

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

  1. Not using HTTPS for authentication.
  2. Failing to use Secure for sensitive cookies.
  3. Failing to use HttpOnly where client-side access is unnecessary.
  4. Ignoring SameSite configuration.
  5. Putting sensitive authorization decisions entirely inside client-controlled cookie data.
  6. Using predictable session identifiers.
  7. Failing to regenerate sessions after authentication.
  8. Not expiring or invalidating sessions appropriately.

Common Session Security Mistakes

  1. Using weak session IDs.
  2. Keeping sessions alive indefinitely.
  3. Not invalidating sessions after logout.
  4. Not regenerating session IDs after login.
  5. Storing session data insecurely.
  6. Allowing session IDs to travel over unencrypted connections.
  7. 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.

CodeWithAV Web Security Tip:

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 vs HTTPS Explained

HTTP Status Codes Every Developer Should Know

What Is an API? Complete Beginner Guide

REST API Explained With Examples

What Is DNS?

Explore More Web Development and Cybersecurity Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.