How Search Engines Find and Rank Web Pages: Complete Beginner Guide

How Search Engines Find and Rank Web Pages

Whenever you search for something on Google, Bing, or another search engine, you usually get thousands or even millions of results within seconds.

But have you ever wondered how a search engine decides which page should appear near the top?

For example, when you search for:

“Best Python projects for beginners”

Why does one website appear on the first page while another appears much lower?

The answer is a combination of web crawling, indexing, search relevance, content quality, technical accessibility, links, freshness, user experience, and many other signals.

This guide explains the complete process in beginner-friendly language so you can understand how search engines work and how website owners can improve their chances of appearing in search results.


What Is a Search Engine?

A search engine is a software system that helps users find information available on the web.

Popular search engines include:

  • Google
  • Bing
  • DuckDuckGo
  • Yahoo
  • Brave Search

A search engine generally performs three important jobs:

  1. Discover web pages
  2. Understand and store those pages
  3. Return useful results when someone searches

Google officially describes these stages as crawling, indexing, and serving search results. Not every discovered page is necessarily indexed or shown for every query.


How Search Engines Work: The Basic Process

A simplified search process looks like this:

Website
   ↓
URL Discovery
   ↓
Crawling
   ↓
Page Processing
   ↓
Indexing
   ↓
User Searches
   ↓
Query Understanding
   ↓
Ranking & Result Selection
   ↓
Search Results Page
   ↓
User Clicks a Result

Let's understand every stage.


1. URL Discovery

Before a search engine can crawl a webpage, it must first know that the page exists.

This is called URL discovery.

Search engines can discover pages in several ways, including:

  • Links from other webpages
  • Internal links on your own website
  • Sitemaps
  • Previously known URLs
  • Other discovery mechanisms provided by the search engine

Google says that links are an important way new pages are discovered, and sitemaps can also help search engines learn about new or updated URLs.

Example

Suppose your blog has this page:

https://example.com/python-projects

If another page already known to Google links to this URL, Google may eventually discover it while crawling the web.

Adding the URL to a sitemap can also help communicate that the page exists.


2. Crawling

Crawling is the process in which automated software visits webpages and retrieves their content.

Google's crawler is commonly known as Googlebot, while Bing uses Bingbot.

During crawling, a search engine may retrieve information such as:

  • Text
  • Headings
  • Links
  • Images
  • Videos
  • HTML structure
  • Other page resources

Google explains that its crawlers can render webpages and process JavaScript because modern websites often depend on dynamically generated content.

What Can Prevent Crawling?

A search engine may have difficulty accessing a page because of:

  • Server problems
  • Network problems
  • Incorrect robots.txt rules
  • Blocked resources
  • Technical configuration errors
  • Pages that are difficult to discover through links

Google specifically recommends checking robots.txt, sitemaps, server capacity, and crawling issues when pages are not being discovered properly.


3. Indexing

After crawling a page, the search engine tries to understand what the page contains.

This stage is called indexing.

You can think of an index as a huge digital library.

Web page → Search engine understands it → Information stored in index

During indexing, search engines may analyze:

  • Page text
  • Title
  • Headings
  • Images
  • Alt text
  • Language
  • Canonical information
  • Links
  • Other page signals

Google notes that indexing can involve processing textual content, images, videos, metadata, and determining whether a page is a duplicate or canonical version of another page.

Important: Crawled Does Not Always Mean Indexed

A common beginner mistake is to assume:

Crawled = Indexed = Ranked

These are different things.

A page may be discovered and crawled but not appear in the index. Similarly, a page can be indexed but not appear prominently for a particular search.

Google explicitly says that indexing is not guaranteed for every page.


4. Search Query Understanding

Now imagine someone searches:

“how to learn JavaScript”

The search engine has to understand what the user is actually looking for.

The query could indicate that the user wants:

  • A beginner tutorial
  • A learning roadmap
  • Courses
  • Books
  • Practice resources
  • Projects

Search systems use language and other technologies to interpret the meaning and intent behind queries rather than simply matching one exact keyword.

Google also explains that its systems can understand relationships between a page and different ways users may search for the same topic.


5. Ranking and Result Selection

After understanding the query, the search engine looks through its index and determines which pages are relevant to the search.

This is where ranking becomes important.

Search engines consider many signals rather than relying on one simple rule.

Google says its ranking systems use hundreds of factors, including factors related to relevance and context such as language, location, and device.

Bing describes ranking in terms including relevance, quality, freshness, authority, popularity, user engagement, language, location, and page-load experience.

These systems are complex and can change over time, so there is no permanent checklist that guarantees the number-one position.


Major Factors That Can Affect Search Visibility

There is no single universal ranking formula, but several areas matter consistently for website owners.

Area Why It Matters
Relevance The page should actually address the user's query.
Content quality Useful, accurate, original and satisfying content is important.
Search intent The content should match what the searcher is trying to accomplish.
Links Internal and relevant external links help discovery and provide context.
Technical accessibility Search engines must be able to crawl and process the page.
Freshness Fresh information can matter especially for topics that change frequently.
Page experience A usable, readable and technically sound page provides a better experience.

Google's guidance emphasizes helpful, reliable, people-first content and an overall good page experience rather than optimizing a page around one or two isolated signals.


Content Quality Matters

Imagine two articles about Python.

Article A:

It contains a few generic paragraphs, copied explanations, excessive keywords and little practical value.

Article B:

It explains the concept clearly, includes original examples, answers common questions, uses understandable headings and helps the reader complete a task.

The second type of content is much closer to what Google's people-first guidance recommends.

Google recommends creating content primarily for people rather than producing content mainly to manipulate search rankings. It also encourages originality, depth, accuracy and a satisfying reader experience.


What Is Search Intent?

Search intent means the purpose behind a search query.

For example:

Query Likely Intent
What is Docker? Learn / understand
How to install Docker on Windows Perform a task
Docker vs Kubernetes Compare options
Docker Desktop download Navigate / obtain software

A strong article should answer the need behind the query, not merely repeat the keyword.


Why Keywords Still Matter

Keywords are the words and phrases people use when searching.

For example, a user might search:

Python for beginners
Learn Python
Python roadmap
Python projects for students

Modern search systems can understand related language and meaning, so you do not need to repeat an exact phrase unnaturally throughout an article.

Google's SEO guidance recommends thinking about the words your audience may search for while also noting that its language-matching systems can understand many variations of a query.

Bad Keyword Usage

Python beginners Python course Python beginners
Python tutorial Python beginners Python course
Python learning Python beginners

This makes the article difficult to read.

Better Approach

Use the topic naturally:

“Python is one of the most popular programming languages for beginners because its syntax is relatively easy to read. In this guide, we'll cover the basics and show you how to start practicing with small projects.”


Title Tags and Search Result Titles

The title of your page is extremely important for communicating what the page is about.

A good title should be:

  • Clear
  • Accurate
  • Specific
  • Relevant to the content
  • Easy to understand

For example:

Weak: “Python”
Better: “Python for Beginners: Complete Beginner Guide”

Google explains that title links can be generated from several sources, including the page's title element and headings. It recommends titles that are unique, clear, concise and accurate.


Meta Descriptions and Search Snippets

A meta description is a short description of a webpage.

For example:

<meta name="description"
content="Learn Python from scratch with this beginner-friendly guide covering syntax, variables, loops, functions and projects.">

Search engines may use the page's content or the meta description when generating the snippet shown in search results.

Google recommends creating useful page titles and descriptions because they can help searchers understand what a result contains before visiting it.


Internal Links Help Search Engines Discover Content

An internal link connects one page of your website to another page on the same website.

For example:

Python Guide
     ↓
Python Projects
     ↓
Python Interview Questions

Internal links can help readers navigate your site and can also help search engines discover related pages.

Google's SEO Starter Guide describes links as an important resource for connecting users and search engines with other relevant pages.

Example HTML

<a href="https://example.com/python-projects">
Python Projects for Beginners
</a>

Use descriptive anchor text instead of generic phrases like “click here.”


What Are Backlinks?

A backlink is a link from another website to your website.

For example:

Other Website
     ↓
Your Website

Relevant links from trustworthy websites can help discovery and may contribute to how search engines assess a page or site.

However, SEO should not become a race to collect as many links as possible.

Google's guidance emphasizes creating useful content that naturally provides value and can earn relevant references, while Bing also discusses quality links and site authority in its webmaster guidance.

Focus on Relevant Links

A link from a website that is genuinely related to your topic can be more useful than an unrelated collection of low-quality links.


Freshness: Does Updating Old Content Help?

Freshness matters differently depending on the topic.

For example:

  • “What is a computer?” may remain useful for many years.
  • “Latest Android versions” can become outdated quickly.
  • “Current cloud pricing” may need frequent updates.
  • “2026 cybersecurity certifications” should be checked periodically.

Bing explicitly identifies freshness as one of the factors used in its search systems, especially where information becomes outdated quickly.

Google also recommends keeping content up to date when necessary, but warns against changing dates merely to make unchanged content appear fresh.


Page Experience and Website Usability

A search visitor expects a page to work properly.

Important areas include:

  • Readable text
  • Mobile-friendly design
  • Reasonable loading performance
  • Easy navigation
  • Secure HTTPS connection
  • Content that is easy to access

Google says its core ranking systems seek to reward pages that provide a good overall page experience rather than encouraging site owners to focus on one isolated aspect.

Bing also notes that slow page-load times can create a poor user experience.


Mobile Search Matters

Many users access websites from smartphones.

A website should therefore work well on:

  • Mobile phones
  • Tablets
  • Laptops
  • Desktop computers

Google's documentation notes that Google uses a mobile crawler as its default crawler for websites and recommends making sites mobile friendly.

For a Blogger website, check your pages on an actual phone instead of testing only on a desktop.


Why Some Pages Don't Appear in Google

There can be many reasons why a webpage does not appear in search results.

Possible reasons include:

  • The page has not been discovered yet.
  • The page has not been indexed.
  • Search engines cannot access the page correctly.
  • The page is blocked from indexing.
  • The content is duplicated or low value.
  • The page does not match the user's query well.
  • Another page may be considered more relevant.
  • The content may not provide enough value for the search demand.

Google notes that even a page that has been crawled may not necessarily be indexed or shown for a search query.


What Is a Sitemap?

A sitemap is a file that provides information about the URLs on a website.

For many websites, XML sitemaps are commonly used.

A simplified example looks like:

<urlset>
    <url>
        <loc>https://example.com/page-1</loc>
    </url>

    <url>
        <loc>https://example.com/page-2</loc>
    </url>
</urlset>

A sitemap helps search engines discover URLs, especially on larger or frequently updated websites.

However, a sitemap is not a guarantee of indexing or rankings. Google explicitly makes this distinction.


What Is Robots.txt?

The robots.txt file provides instructions to crawlers about which URLs or paths they may access.

A simplified example is:

User-agent: *
Disallow: /private/

Incorrect robots.txt settings can accidentally interfere with crawling.

This is why website owners should understand their robots rules before changing them.

Google recommends checking robots.txt when diagnosing crawling problems.


Google Search Console: A Useful Tool for Bloggers

Google Search Console is a free service that helps website owners understand how their site performs in Google Search.

It can help you inspect areas such as:

  • Indexing
  • Search queries
  • Impressions
  • Clicks
  • Search appearance
  • Technical issues

Google recommends Search Console as a way to monitor search performance and determine whether your pages can be indexed.

Typical Workflow

Publish Article
      ↓
Submit / Discover URL
      ↓
Check Indexing
      ↓
Monitor Search Performance
      ↓
Improve Content
      ↓
Update When Necessary

Bing Webmaster Tools

Bing provides its own webmaster platform.

Bing Webmaster Tools can provide information about:

  • Search performance
  • Keywords
  • Indexing
  • Crawling
  • Sitemaps
  • Technical recommendations
  • AI-related visibility in supported Microsoft experiences

Bing's current Webmaster Tools documentation includes search-performance reporting and an AI Performance report that shows how site pages are cited in supported AI-generated answers such as Microsoft Copilot and Bing AI experiences.


How Search Engines Treat AI-Generated Content

Artificial intelligence makes it easier than ever to produce large amounts of content.

But publishing large volumes of automatically generated articles does not guarantee search visibility.

Google's current guidance emphasizes people-first content and specifically warns against producing large amounts of content mainly for search engine traffic or relying heavily on automation without adding meaningful value.

A better workflow is:

AI / Research
      ↓
Human Review
      ↓
Fact Checking
      ↓
Original Examples
      ↓
Useful Structure
      ↓
Final Article

The goal should be to help the reader rather than simply increase the number of pages on a website.


Does Writing More Words Improve Ranking?

Not automatically.

A 5,000-word article is not automatically better than a 1,000-word article.

The important question is:

Does the article provide enough useful information to satisfy the reader's need?

Google explicitly says there is no preferred word count that guarantees better ranking.


Why Duplicate Content Can Be a Problem

Suppose ten pages contain almost the same article:

Page 1 → Same content
Page 2 → Same content
Page 3 → Same content
Page 4 → Same content
...

Search engines may have difficulty determining which version is the most representative or useful.

Google's indexing process includes identifying duplicate and canonical versions of pages.

This is one reason original, useful content is preferable to repeatedly republishing nearly identical material.


How Internal Website Structure Affects Discoverability

A well-organized website makes it easier for visitors and crawlers to move between related pages.

For example, a technology blog might have:

Home
│
├── AI
│   ├── AI Tools
│   ├── Machine Learning
│   └── AI Projects
│
├── Programming
│   ├── Python
│   ├── JavaScript
│   └── C Programming
│
├── Cybersecurity
│   ├── Ethical Hacking
│   └── Network Security
│
└── Careers
    ├── Resume
    └── Interview Preparation

This kind of structure can make relationships between pages clearer.


Common SEO Mistakes Beginners Make

1. Keyword Stuffing

Repeating keywords unnaturally can make content difficult to read.

2. Writing Only for Search Engines

If an article is created only to attract clicks and does not satisfy readers, it may provide little long-term value.

3. Publishing Copied Content

Simply rewriting or copying existing information without adding meaningful value is a weak content strategy.

4. Ignoring Technical Errors

A great article cannot help much if search engines cannot access or process the page properly.

5. Creating Misleading Titles

Do not promise something in the title that the article does not actually deliver.

6. Ignoring Mobile Users

A page should be easy to use on smaller screens.

7. Forgetting Internal Links

Related articles should be connected naturally where useful.

8. Treating SEO as a One-Time Task

SEO is better understood as an ongoing process of publishing, monitoring, learning and improving.


How to Improve the SEO of a Blog Post

Before publishing an article, use this practical checklist.

Check Question
Topic Does the article solve a real reader problem?
Title Is the title clear and accurate?
Content Is the information useful and sufficiently complete?
Originality Have you added your own examples, explanations or experience?
Links Are relevant internal and external links included?
Mobile Does the page work well on a phone?
Indexing Can search engines access and index the page?
Updates Does any information need future updating?

Simple Example: From Search Query to Result

Imagine a user searches for:

“Best GitHub projects for students”

A simplified process could look like this:

User enters query
       ↓
Search engine interprets query
       ↓
Searches its index
       ↓
Finds potentially relevant pages
       ↓
Evaluates many signals
       ↓
Selects and orders useful results
       ↓
Displays search results

The exact ranking process is much more complex, and search engines continuously improve their algorithms. Google explicitly notes that its systems evolve over time.


Google vs Bing: Is Ranking Exactly the Same?

No.

Google and Bing are separate search engines with their own systems, infrastructure and ranking approaches.

There is substantial overlap in good SEO fundamentals, including:

  • Accessible content
  • Good page structure
  • Relevant information
  • Useful content
  • Descriptive links
  • Good technical implementation

However, their systems can evaluate signals differently.

Bing publicly discusses factors including relevance, quality, freshness, authority, popularity and user engagement, while Google's published documentation emphasizes relevance, helpfulness, technical accessibility, links and overall page experience among many other signals.


Modern Search Is Expanding Beyond Traditional Blue Links

Search is no longer limited to a simple list of webpages.

Search engines increasingly provide experiences involving:

  • Images
  • Videos
  • Maps
  • News
  • Knowledge panels
  • AI-generated answers

Bing currently documents AI Performance reporting for visibility and citations in supported AI experiences, demonstrating that content can be surfaced in AI-powered search environments as well as traditional results.

This makes clear structure, reliable information and useful content increasingly valuable.


How Bloggers Can Build Search-Friendly Content

For a technology blog such as CodeWithAV, a practical workflow can be:

  1. Choose a topic that solves a genuine problem.
  2. Understand what readers are likely trying to learn or do.
  3. Research the topic using reliable sources.
  4. Create an original explanation.
  5. Use clear headings and short paragraphs.
  6. Add examples, diagrams, tables or code where useful.
  7. Add relevant internal links.
  8. Write a clear title and useful description.
  9. Check the mobile experience.
  10. Publish and monitor performance.
  11. Update the article when information genuinely changes.

This approach is much more sustainable than publishing large numbers of thin pages simply because a keyword appears popular.


Frequently Asked Questions

1. How do search engines find websites?

Search engines discover websites and webpages through methods such as links, previously known URLs and sitemaps. Crawlers then visit accessible pages to retrieve and process their content.

2. What is crawling?

Crawling is the process of using automated software to discover and retrieve webpages and their resources.

3. What is indexing?

Indexing is the process of analyzing information from crawled pages and storing information about them in a search engine's index.

4. Does indexing guarantee ranking?

No. A page can be indexed but still not appear prominently for a particular query.

5. Does Google accept payment for higher organic rankings?

Google states that it does not accept payment to rank webpages higher in its organic Search results.

6. Does a sitemap guarantee indexing?

No. A sitemap can help search engines discover URLs, but Google states that it does not guarantee indexing or ranking.

7. Is more content always better?

No. Search-friendly content should provide genuine value. Google specifically discourages creating large amounts of content primarily to attract search traffic.

8. Does longer content always rank higher?

No. Google says there is no preferred word count that automatically produces better rankings.

9. Are backlinks important?

Links can help search engines discover content and provide context. However, link quality and relevance matter more than blindly collecting large numbers of links. Google and Bing both discuss links and site authority in their webmaster guidance.

10. How can I check whether Google has indexed my page?

Google Search Console provides tools and reports that help website owners understand indexing and search performance.


Recommended Reading on CodeWithAV

Tip: Replace the homepage links above with the exact URLs of the corresponding CodeWithAV articles after those posts are published.


Official Sources


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.

Adarsh verma

Adarsh verma

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

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.

What Is a CDN? How Content Delivery Networks Work Explained

When you open a modern website, the content may come from infrastructure located much closer to you than the website's main server.

This is possible because of a technology called a CDN.

CDN stands for Content Delivery Network. A CDN is a distributed network of servers and related infrastructure designed to deliver web content and other digital resources efficiently to users.

Simple Definition: A CDN is a geographically distributed network of servers that can cache and deliver content closer to users, helping improve performance, availability, and scalability for many types of applications.

CDNs are widely used for websites, APIs, videos, images, JavaScript files, CSS, software downloads, and other digital content.

In this guide, you will learn what a CDN is, how it works, what edge servers are, how caching works, how CDNs improve performance, CDN security, CDN vs hosting, common use cases, and how developers can use a CDN.

What Does CDN Stand For?

CDN stands for Content Delivery Network.

The name describes its purpose:

  • Content: Files and resources such as images, CSS, JavaScript, videos, documents, and sometimes application responses.
  • Delivery: The network helps deliver those resources to users.
  • Network: Multiple distributed servers and network locations work together.

Why Do We Need a CDN?

Imagine that your website's main server is located in one country while your users are spread across several continents.

Without a CDN, many users may need to retrieve static resources directly from the origin server.

                    Users
               /      |      \
              /       |       \
             v        v        v
         India      Europe    USA
              \       |       /
               \      |      /
                v     v     v
              Origin Server
  

With a CDN:

                    Users
                /      |      \
               v       v       v
            Edge A   Edge B   Edge C
               \       |       /
                \      |      /
                 v     v     v
                 Origin
  

Users can often retrieve cached content from a nearby edge location instead of contacting the origin for every request.

How Does a CDN Work?

A simplified CDN workflow is:

User requests content
        ↓
DNS / Routing
        ↓
CDN Edge Location
        ↓
Is content cached?
   /           \
 Yes            No
  |              |
  v              v
Return        Request
Cache         Origin
                  |
                  v
             Get Content
                  |
                  v
             Cache Content
                  |
                  v
             Return to User
  

This architecture allows frequently requested content to be served from distributed locations.

What Is an Edge Server?

An edge server is a server or infrastructure component located closer to end users than the origin infrastructure for a particular application.

CDNs maintain edge locations in different geographic and network locations.

A simplified architecture looks like:

                 Origin
                   |
          +--------+--------+
          |        |        |
          v        v        v
       Edge A   Edge B   Edge C
          |        |        |
          v        v        v
       Users    Users    Users
  

The exact infrastructure differs between CDN providers.

What Is an Origin Server?

The origin server is the primary source of content for a CDN-backed application.

For a website, the origin may host:

  • HTML
  • Application code
  • Images
  • API services
  • Databases
  • Dynamic application logic

A CDN does not necessarily replace the origin server. Instead, it often sits between users and the origin.

CDN Architecture

             Internet Users
             /     |      \
            /      |       \
           v       v        v
        Edge 1   Edge 2   Edge 3
           \       |        /
            \      |       /
             \     |      /
               Origin
                  |
               Database
  

Static content can often be served from the edge, while uncached or dynamic requests may travel to the origin.

What Is CDN Caching?

CDN caching means storing copies of eligible content at edge locations so subsequent requests can be served without contacting the origin every time.

For example, suppose a website contains:

logo.png
style.css
app.js
banner.jpg
  

The CDN may cache these files.

A user near an edge location can request the file from that edge instead of downloading it directly from the origin.

Cache Hit vs Cache Miss

Cache Hit

A cache hit occurs when the requested content is already available in the CDN cache and can be served according to the caching rules.

User
 ↓
CDN Edge
 ↓
Content Found
 ↓
Return Content
  

Cache Miss

A cache miss occurs when the edge does not have a usable cached copy.

User
 ↓
CDN Edge
 ↓
Not Cached
 ↓
Origin Server
 ↓
Content
 ↓
CDN Cache
 ↓
User
  

Why Does CDN Caching Improve Performance?

Suppose an image is stored at an origin server thousands of kilometers away.

Without a CDN, every request may need to travel toward the origin.

With a CDN, the resource may already be cached at an edge location closer to the user.

Without CDN

User ----------------------> Origin


With CDN

User -----> Nearby Edge
                 |
            Cached Content
  

This can reduce network distance and origin workload for cacheable content.

What Is Latency?

Latency is the time associated with data traveling between communicating systems and the processing involved.

Network distance is one factor that can affect latency.

CDNs can help reduce latency for cacheable content by placing copies closer to users.

CDN and Network Distance

Imagine the origin server is in one geographic region while users are distributed across the world.

                 Origin
                   |
          +--------+--------+
          |        |        |
          v        v        v
       Asia     Europe    America
       Edge      Edge       Edge
          |        |        |
          v        v        v
       Users    Users     Users
  

The CDN's distributed infrastructure can reduce the effective distance to cached resources.

What Type of Content Does a CDN Cache?

CDNs are commonly used for content such as:

  • Images
  • CSS files
  • JavaScript files
  • Fonts
  • Videos
  • Downloads
  • Static HTML

Depending on the CDN and application architecture, other content may also be cacheable.

Static vs Dynamic Content

Static Content

Static content is content that can be served without generating a unique response for every individual request.

Examples include:

  • Logo images
  • CSS files
  • JavaScript bundles
  • Public images
  • Fonts

Dynamic Content

Dynamic content is generated or customized based on factors such as the user, request, application state, database data, or current conditions.

Examples include:

  • User dashboards
  • Shopping carts
  • Personalized account pages
  • Real-time application data

Dynamic requests can still pass through a CDN, but caching must be configured carefully.

Can a CDN Cache Dynamic Content?

In some architectures, CDNs can cache certain generated or dynamic responses when the application explicitly allows it and the content is safe to cache.

However, private or personalized information should not be cached publicly by mistake.

Security Warning: Incorrect caching rules can expose personalized or sensitive information. Always define cache behavior carefully for authentication pages, user-specific responses, private API responses, and other sensitive content.

What Is Cache-Control?

Cache-Control is an HTTP response header used to control caching behavior.

For example:

Cache-Control: max-age=3600
  

This indicates a caching policy in which the response can be considered fresh for the specified duration, subject to the applicable HTTP caching rules.

What Is TTL in CDN Caching?

A CDN may use a time-to-live or freshness period to determine how long a cached resource remains fresh before it needs revalidation or retrieval according to the caching configuration.

For example:

image.jpg
Cache Lifetime: 1 hour
  

The exact cache behavior depends on the CDN, response headers, cache rules, and other configuration.

What Is Cache Invalidation?

Cache invalidation means removing or refreshing cached content so that a newer version can be served.

Suppose you update:

logo.png
  

Users may still receive the older cached version until it expires or is invalidated.

A CDN can provide mechanisms to purge or invalidate cached resources.

Cache Busting

Developers can also change a resource URL when the underlying file changes.

For example:

app.css?v=1
app.css?v=2
  

A more robust production approach is often to use content-based or versioned filenames, such as:

app.91a83f.css
app.f73d21.css
  

This allows browsers and CDNs to cache files for longer while new versions use different URLs.

CDN and DNS

DNS is commonly involved in directing users toward CDN infrastructure.

A simplified example looks like:

www.example.com
       |
       v
      DNS
       |
       v
CDN Endpoint
       |
       v
Nearest / Appropriate Edge
  

The actual routing mechanism depends on the CDN provider and architecture.

How DNS Can Help a CDN

A DNS name can point users toward a CDN service instead of directly exposing the origin server.

For example:

User
 |
 v
www.example.com
 |
 v
CDN DNS / Routing
 |
 v
Edge Location
 |
 v
Origin if needed
  

CDN and Reverse Proxy

A CDN often behaves as part of a reverse-proxy architecture.

User
  |
  v
CDN / Reverse Proxy
  |
  v
Origin Server
  |
  v
Application
  

The CDN can terminate connections, apply caching rules, route requests, and provide other edge services before traffic reaches the origin.

CDN and HTTPS

CDNs can also participate in HTTPS delivery.

A simplified architecture is:

Browser
   |
   | HTTPS
   v
CDN Edge
   |
   | HTTPS / configured origin connection
   v
Origin
  

The precise TLS architecture depends on the CDN configuration. In many deployments, HTTPS is terminated at the CDN edge, and the CDN can establish another secured connection to the origin.

What Is TLS Termination?

TLS termination means decrypting an HTTPS connection at a network endpoint such as a CDN, reverse proxy, or load balancer.

For example:

Client
  |
  | HTTPS
  v
CDN Edge
  |
  | TLS Termination
  v
Origin Connection
  

Organizations must configure the origin connection appropriately because securing only the client-to-edge connection may not be sufficient for sensitive applications.

How CDNs Improve Scalability

If a website receives millions of requests for the same static resources, serving every request directly from the origin can create unnecessary load.

A CDN can serve cached resources from multiple edge locations.

             Millions of Users
               /    |    \
              /     |     \
             v      v      v
          Edge A  Edge B  Edge C
              \      |      /
               \     |     /
                 Origin
  

This can reduce repeated requests reaching the origin.

CDN and DDoS Protection

Many CDN platforms provide security capabilities that can help absorb, filter, or mitigate certain forms of abusive traffic, including distributed denial-of-service attacks.

However, security features vary between providers and service plans.

A CDN should therefore be considered one part of a broader security architecture.

CDN and Web Application Firewall

A Web Application Firewall (WAF) can inspect HTTP traffic and apply rules intended to block or challenge suspicious requests.

Some CDN platforms provide WAF capabilities at the network edge.

User
  |
  v
CDN Edge
  |
  v
WAF
  |
  +---- Allowed ----> Origin
  |
  +---- Blocked ----> Stop
  

WAF behavior depends on the rules and configuration.

CDN vs Web Hosting

A CDN and web hosting solve different problems.

CDN Web Hosting
Delivers content from distributed infrastructure Provides infrastructure to host the application or website
Often caches static resources Stores and executes website/application resources
Can reduce load on origin Acts as origin for application content in many setups

Many websites use both.

CDN vs Cloud Hosting

Cloud hosting provides computing infrastructure and services for applications.

A CDN distributes content and provides edge delivery services.

A cloud-hosted application can still use a CDN in front of it.

Users
  |
  v
CDN
  |
  v
Cloud Load Balancer
  |
  v
Application Servers
  |
  v
Database
  

CDN for Images

Images can be among the largest resources on a website.

A CDN can cache and deliver images from edge locations.

Modern image delivery systems can also perform transformations such as resizing or format conversion when the service supports those capabilities.

The exact features depend on the CDN or image delivery platform.

CDN for JavaScript and CSS

Large JavaScript and CSS files can significantly affect page loading.

Serving cacheable static assets through a CDN can reduce origin requests and improve delivery performance.

HTML
 |
 +---- style.css ----> CDN
 |
 +---- app.js --------> CDN
 |
 +---- image.jpg -----> CDN
  

CDN for Video

Video files can be much larger than normal web resources.

CDN infrastructure is commonly used to distribute video content to users from locations that are closer to them.

Large-scale video systems can use specialized streaming and delivery architectures.

CDN for Software Downloads

Operating-system images, application installers, game updates, libraries, and other large downloads can benefit from distributed delivery.

Instead of making every user download from one origin location, cached copies can be distributed through edge infrastructure.

CDN for APIs

CDNs can also sit in front of APIs, but API caching requires careful design.

Public responses may sometimes be safely cached, while personalized responses usually require different controls.

For example:

GET /api/public/products
        |
        v
      CDN
        |
   Cached Response
  

On the other hand:

GET /api/my-account
        |
        v
Personalized Data
        |
        v
Careful Cache Policy
  

Incorrectly caching private API responses can expose one user's information to another user.

CDN and CORS

When frontend applications load resources from different origins, CORS can become relevant.

CORS stands for Cross-Origin Resource Sharing.

For example:

https://app.example.com
        |
        | Request
        v
https://cdn.example.net
  

If browser security policies consider the request cross-origin, appropriate CORS response headers may be necessary depending on the resource and request.

CDN and Browser Cache

CDN caching and browser caching are different layers.

User
 |
 v
Browser Cache
 |
 | Miss
 v
CDN Cache
 |
 | Miss
 v
Origin
  

A resource can potentially be cached both in the browser and at a CDN edge, according to the applicable caching policies.

CDN and Compression

Many CDNs can compress supported resources to reduce the amount of data transferred over the network.

Compression can be especially useful for text-based resources such as:

  • HTML
  • CSS
  • JavaScript
  • JSON
  • SVG

The specific compression algorithms available depend on the platform and client support.

CDN and HTTP/2 or HTTP/3

Modern CDN infrastructure can support newer HTTP versions, depending on the provider and configuration.

HTTP/2 and HTTP/3 include protocol improvements that can help modern web applications handle multiple requests efficiently.

A CDN can combine modern HTTP delivery with edge caching and distributed infrastructure.

CDN Benefits

1. Lower Latency for Cached Content

Content can often be served from a location closer to users.

2. Reduced Origin Load

Cached resources do not need to be retrieved from the origin for every request.

3. Better Scalability

Distributed delivery can help websites handle large traffic volumes.

4. Improved Availability

Distributed infrastructure can provide additional resilience, depending on the design.

5. Security Features

Some CDNs offer capabilities such as traffic filtering, WAFs, rate limiting, bot controls, and DDoS mitigation.

6. Global Delivery

CDNs can distribute content across multiple geographic and network locations.

CDN Limitations

1. Cache Complexity

Incorrect caching rules can produce stale content or expose private information.

2. Configuration Complexity

Advanced CDN features can introduce additional configuration requirements.

3. Cost

CDN services can generate charges depending on traffic, requests, storage, features, and provider pricing.

4. Not Everything Can Be Cached

Highly personalized or dynamic content may need to be generated at the origin or handled through specialized edge logic.

5. Provider Dependency

Applications can become dependent on CDN-specific configuration and features.

CDN Common Use Cases

Use Case Why a CDN Can Help
Websites Faster delivery of static resources
Images Distributed image delivery
Video Large-scale media distribution
APIs Caching and edge processing for suitable responses
Downloads Distributed large-file delivery
Security Edge filtering and other security capabilities

How to Add a CDN to a Website

The exact setup depends on your hosting provider and CDN platform.

A simplified setup is:

  1. Create or configure the CDN service.
  2. Add your domain or application.
  3. Configure the origin server.
  4. Configure DNS according to the CDN provider's instructions.
  5. Configure HTTPS.
  6. Define caching rules.
  7. Test the website.
  8. Monitor cache behavior and origin traffic.

Always use the current documentation of your selected CDN because DNS, TLS, caching, and routing configuration varies between providers.

Simple CDN Example

Suppose your website has:

https://example.com
  

And your static resources are:

/css/style.css
/js/app.js
/images/logo.png
/images/banner.jpg
  

A CDN can serve those resources through edge infrastructure while dynamic application requests continue to reach the origin when appropriate.

CDN Security Best Practices

  • Use HTTPS.
  • Protect the origin from unnecessary direct public access where architecture allows.
  • Set cache rules carefully.
  • Never publicly cache private responses accidentally.
  • Use appropriate access controls.
  • Monitor unusual traffic.
  • Configure WAF and rate limiting where appropriate.
  • Protect administrative endpoints.

CDN and Origin Protection

In some architectures, organizations attempt to ensure that users reach the application through the CDN rather than directly through the origin address.

A simplified model is:

Internet
   |
   v
 CDN
   |
   v
Origin
  

The origin should still have appropriate firewall and access controls. A CDN should not be treated as the only security boundary.

How to Check Whether a Website Uses a CDN

Developers can inspect a website's network behavior and DNS configuration to identify CDN-related infrastructure.

Useful tools include:

  • Browser developer tools
  • DNS lookup tools
  • nslookup
  • dig
  • HTTP header inspection tools
  • Network monitoring tools

Response headers and DNS records can provide clues, although CDN infrastructure is not always obvious from a single observation.

CDN and Website Performance Testing

After configuring a CDN, compare important performance measurements before and after the change.

Look at metrics such as:

  • DNS lookup time
  • Connection time
  • Time to first byte
  • Resource download time
  • Cache hit ratio
  • Origin request volume

Performance improvements depend on the content being delivered, geographic distribution, cacheability, network paths, and application architecture.

CDN and Cache Hit Ratio

A cache hit ratio represents how often requests can be served from the cache rather than requiring an origin fetch, according to the system's measurement method.

A higher cache hit ratio can reduce origin traffic for cacheable workloads.

However, a high cache hit ratio is not automatically the goal for every request. Personalized and sensitive resources need appropriate cache policies even if that means they are not publicly cached.

CDN for a Blogger Website

Blog platforms may already provide parts of a distributed delivery architecture, while custom domains and third-party assets can involve additional DNS or CDN configuration.

For a blog such as CodeWithAV, CDN-related concepts are particularly useful when optimizing:

  • Images
  • CSS
  • JavaScript
  • Fonts
  • Static assets
  • Custom-domain networking

However, the exact CDN configuration available to a Blogger site depends on the platform and domain setup.

Frequently Asked Questions

```

What is a CDN in simple words?

A CDN is a distributed network of servers that helps deliver website and application content from locations closer to users.

What does CDN stand for?

CDN stands for Content Delivery Network.

How does a CDN work?

A CDN receives requests, determines an appropriate edge location, checks whether the requested content is cached, and retrieves content from the origin when necessary.

What is an edge server?

An edge server is infrastructure located relatively close to users and used to deliver content or perform other processing at the network edge.

What is an origin server?

The origin server is the primary source from which a CDN obtains content when that content is not available in an edge cache or should be fetched from the source.

Does a CDN replace web hosting?

Usually not. A CDN and web hosting perform different functions and are often used together.

Does a CDN make a website faster?

A CDN can improve delivery performance for suitable content, especially when users are geographically distant from the origin. The actual improvement depends on the site's content, cacheability, network paths, and configuration.

Does a CDN cache everything?

No. Content is cached according to HTTP caching rules and CDN configuration. Private, personalized, or dynamic content often requires special handling.

What is a cache hit?

A cache hit occurs when the CDN has a usable cached copy of the requested content and can serve it according to its cache rules.

What is a cache miss?

A cache miss occurs when the requested content is not available as a usable cached copy at the relevant edge, so the CDN may need to retrieve it from another location or the origin.

What is CDN cache invalidation?

Cache invalidation removes or refreshes cached content so that a newer version can be delivered.

Can a CDN improve security?

Many CDN platforms provide security features such as traffic filtering, WAF capabilities, rate limiting, and DDoS mitigation. These features do not replace a complete security architecture.

Can a CDN cache API responses?

Yes, some API responses can be cached when their cache behavior is appropriate. Personalized or sensitive API responses require careful cache controls.

What is CDN cache busting?

Cache busting is a technique for ensuring updated resources receive a new URL, often through versioned or content-hashed filenames.

```

Final Thoughts

A CDN is an important part of modern web infrastructure.

The basic idea is simple:

User
  ↓
Nearest / Appropriate Edge
  ↓
Cached Content
  ↓
Fast Delivery

Cache Miss
  ↓
Origin
  ↓
CDN
  ↓
User
  

CDNs can improve performance, reduce origin traffic, support scalability, and provide additional security capabilities.

However, a CDN is not simply a “faster server.” Its effectiveness depends on caching rules, content type, geographic distribution, DNS, HTTP behavior, TLS configuration, origin architecture, and application design.

For developers, cloud engineers, DevOps professionals, and cybersecurity learners, understanding CDNs provides a strong foundation for learning reverse proxies, load balancing, caching, edge computing, web performance, and distributed systems.

CodeWithAV Performance Tip:

When optimizing a website, do not focus only on server speed. Examine the complete delivery path: DNS → CDN/Edge → TLS → Cache → Origin → Application → Database.

Related Articles on CodeWithAV

What Is DNS? Complete Domain Name System Guide

How DNS Resolution Works

Public IP vs Private IP

HTTP vs HTTPS Explained

What Is Cloud Computing?

Explore More Web Development and Cloud 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.