How the Web Works

Why should you care about How Web Works?

Knowing how the web works helps you understand what happens when a page loads, why requests fail, and how browsers talk to servers. It makes debugging and building real web apps much easier.

A page starts with a request
The browser is the client in this exchange.
Browser: Requests HTML
Server: Sends HTML
Browser: Renders page
GET / HTTP/1.1
Host: shop.example.com
HTTP/1.1 200 OK
Content-Type: text/html
The browser can then request CSS, scripts, and images.

When you open a website, the main participants are the client and the server.

The browser sends a request for a resource, such as an HTML page, and a server processes that request and sends a response. Many web interactions follow this client-server pattern.

Client - A client is a program that requests resources or services from a server. In web applications, the browser is usually the client.

Server - A server is a computer or software system that receives requests and provides resources or services in response.

A real example: when you open simplyjavascript.com, your browser sends a request to a server. The server may return HTML, CSS, JavaScript, images, or other resources. When a frontend requests user information, the server may return JSON through an API.

A server can provide different types of resources depending on the request. For example, a website may return HTML, CSS, JavaScript, and images, while an API may return JSON data.

Key things to know:

  • Client = the one asking (usually your browser)
  • Server = the system providing a resource or service
  • Many website interactions involve requests from a client and responses from a server
  • Server capacity depends on its hardware, architecture, workload, and scaling strategy.

Trace a browser request to its server.

When you enter a website address in your browser, it needs to find the IP address associated with that domain. It can use cached DNS information or ask a DNS resolver to find the address.

text

User enters simplyjavascript.com
              |
              v
       Browser checks cache
              |
              v
       DNS resolver lookup
              |
              v
       IP address returned
              |
              v
     Browser connects to server

These terms describe the basic DNS flow:

  • Domain name: a human-readable website address.
  • IP address: an address used to locate a device or server on a network.
  • DNS resolver: a service that helps find the IP address for a domain.
  • DNS cache: previously resolved DNS information stored temporarily to avoid repeated lookups.
Inside an HTTP exchange
Requests and responses carry different information.
Request: Method, target, headers, and sometimes a body.
Response: Status, headers, and sometimes a body.
GET /products/123 HTTP/1.1
Host: shop.example.com
HTTP/1.1 200 OK
Content-Type: application/json
{ "id": 123, "name": "Notebook" }
A status code describes the outcome of the request.

HTTP (HyperText Transfer Protocol) is a protocol used for communication between clients and servers on the web. A client sends an HTTP request, and the server sends an HTTP response.

When a client wants something, it sends a Request. When the server responds, it sends back a Response.

A Request includes:

  • Method - what kind of action (GET, POST, PUT, DELETE)
  • URL - where to send the request (e.g. https://api.example.com/users)
  • Headers - extra info like content type or auth tokens
  • Body - optional data sent along with the request, commonly when submitting data

A Response includes:

  • Status code - did it work? (200 = OK, 404 = Not Found, 500 = Server Error)
  • Headers - info about the response
  • Body - the returned data, such as HTML, JSON, text, images, or other content

HTTP Methods - the most common ones:

  • GET - retrieve a resource
  • POST - submit data, often to create a resource or trigger an operation
  • PUT - replace a resource or create it at a known URI, depending on the API
  • PATCH - partially update a resource
  • DELETE - delete a resource

GET is a safe method, and GET, PUT, and DELETE are idempotent. POST is not generally idempotent. Idempotent means repeating the same request has the same intended effect as making it once.

Example: when you visit a product page on a shopping site, your browser sends a GET request to the server. The server finds the product info and sends back a response with status 200 OK and the product data in the body.

http

// A simple GET request (what your browser sends behind the scenes)
GET /products/123 HTTP/1.1
Host: shop.example.com

// The server responds:
HTTP/1.1 200 OK
Content-Type: application/json

{ "id": 123, "name": "Laptop", "price": 999 }

http

POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer <token>

{
  "name": "Sajid",
  "email": "sajid@example.com"
}

HTTP/1.1 201 Created
Content-Type: application/json

{
  "id": 101,
  "name": "Sajid",
  "email": "sajid@example.com"
}
HTTP request and response components
ComponentMeaning
MethodAction the client wants to perform
URL/pathResource being requested
HeadersAdditional request or response information
BodyOptional data sent or returned
Status codeResult of processing the request

Common HTTP status codes you'll see a lot:

  • 200 - the request succeeded
  • 201 - a resource was created successfully.
  • 204 - the request succeeded, but the response has no body.
  • 400 - the server could not process the request because it was invalid
  • 401 - valid authentication credentials are missing or invalid.
  • 403 - the server understood the request but refuses access.
  • 404 - the requested resource was not found
  • 500 - the server encountered an unexpected error

Inspect the status, headers, and body of a response.

HTTPS is HTTP protected by TLS
TLS protects traffic between the client and server.
Authenticate: Check the certificate for the server identity.
Encrypt: Keep request and response data private in transit.
Check integrity: Detect changes to the data in transit.
"https://shop.example.com/products"
A protected connection does not vouch for the site.

HTTPS is HTTP sent through TLS (Transport Layer Security). The browser and server establish an encrypted connection before exchanging the request and response. The lock icon means the connection is protected; it does not guarantee that a website itself is honest or that every piece of content is safe.

  • Confidentiality: encryption makes it difficult for someone on the network to read the traffic.
  • Integrity: TLS helps detect whether traffic was changed in transit.
  • Authentication: certificates help the browser verify that it connected to the domain it requested.

A certificate does not replace good application security. Never put passwords or secret API keys in URLs, validate data on the server, and use secure cookies for session credentials.

HTTP and HTTPS at a glance.
Detail HTTP HTTPS
Typical URL http://example.com https://example.com
Traffic protection Readable or modifiable by a network attacker. Encrypted and integrity-protected by TLS.
Use for Local experiments or legacy internal systems. Public sites, logins, payments, APIs, and any real user data.

text

Browser                         Server
   |                               |
   |------ Connect using TLS ----->|
   |                               |
   |<----- Server certificate -----|
   |                               |
   |--- Verify certificate --------|
   |                               |
   |<==== Encrypted connection ===>|
   |                               |
   |------ HTTP request ---------->|
   |<----- HTTP response ----------|

TLS establishes a secure connection. The server presents a certificate, the browser verifies the certificate and server identity, and encryption protects data in transit. A certificate does not guarantee that the website or its business is legitimate.

Rule: use HTTPS everywhere in production and avoid mixed content, where an HTTPS page tries to load scripts or other sensitive resources over plain HTTP.

API stands for Application Programming Interface. That sounds complicated, but the idea is simple.

An API defines how one application can request data or perform operations provided by another application or service. It specifies the requests that are available, the data they accept, and the responses they return.

Web APIs commonly expose specific URLs called endpoints. Another application can call those endpoints to get or send data without needing access to the server's internal implementation. An API is not necessarily a REST API; REST is one way to design an API, and other styles and protocols also exist.

On the web, APIs usually work over HTTP. You send a request to a specific URL (called an endpoint), and you get data back (usually in JSON format).

javascript

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    return response.json();
  })
  .then(user => console.log(user))
  .catch(error => console.error(error));

The Fetch API generally rejects its promise for network-level failures, but an HTTP error such as 404 or 500 does not automatically reject the promise. Check response.ok or response.status to handle unsuccessful HTTP responses.

APIs are everywhere:

  • Weather apps get data from a weather API
  • Zomato / Swiggy show restaurants by calling a maps API
  • Login with Google uses Google's auth API
  • Your banking app talks to the bank's API to show your balance

As a JavaScript developer, you'll use APIs constantly - to fetch data, send data, and connect your front-end to a back-end or third-party service.

Follow an API call from endpoint to usable data.

REST addresses resources
The URL identifies the resource; the method acts on it.
GET /posts/5: Read post 5.
POST /posts: Create a post in the collection.
PATCH /posts/5: Update part of post 5.
DELETE /posts/5: Remove post 5.
const response = await fetch("/posts/5");
const post = await response.json();
In REST, each request carries the context it needs.

REST stands for Representational State Transfer. Again, fancy name - simple idea.

REST (Representational State Transfer) is an architectural style for designing networked APIs. An API designed around these principles is often called a RESTful API.

The main ideas behind REST:

  • Resources - everything is a “resource” (a user, a product, a post). Each resource has its own URL.
  • HTTP methods - use GET to read, POST to create, PUT/PATCH to update, DELETE to remove
  • Stateless requests - each request contains the information needed to process it; the server does not depend on conversational state from previous requests.
  • Representations - resources can be represented using formats such as JSON

Statelessness does not mean a server cannot store application data. It can store data in a database; statelessness means it does not rely on prior request context. For example, an authenticated API request may include an access token in its Authorization header.

Example of a RESTful API for a blog:

http

GET    /users          Get all users
GET    /users/10       Get user with ID 10
POST   /users          Create a user
PUT    /users/10       Replace user 10
PATCH  /users/10       Partially update user 10
DELETE /users/10       Delete user 10

Each URL identifies a resource, and the HTTP method communicates the intended operation. This is a common REST design pattern, although these elements alone do not make an API fully RESTful.

Real example using fetch():

javascript

// GET all posts
fetch("https://jsonplaceholder.typicode.com/posts")
  .then(res => res.json())
  .then(posts => console.log(posts));

// POST a new post
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello", body: "World", userId: 1 })
})
  .then(res => res.json())
  .then(data => console.log(data));

Compare REST methods and resource URLs.

Who can read the response?
The browser checks cross-origin access for scripts.
Page script: app.test
API: api.test
Browser: Checks response
Origin: https://app.test
// API response header:
Access-Control-Allow-Origin: https://app.test
Without permission, the script cannot read it.
Some requests need a preflight check first.

CORS is something you'll definitely run into as a web developer - usually when your code breaks with a confusing error in the console.

What is CORS?

Browsers enforce the Same-Origin Policy, which restricts JavaScript from reading responses from different origins unless the server allows that access through CORS. An origin is defined by its scheme, host, and port.

For example, JavaScript running on https://mysite.com may request https://api.someothersite.com, but browser JavaScript cannot read the response unless the server permits that origin.

CORS (Cross-Origin Resource Sharing) is a mechanism that allows a server to specify which other origins may access its responses from browser-based JavaScript.

The server does this by adding special headers to its response:

http

// Server response header that allows all origins:
Access-Control-Allow-Origin: *

// Or allow only a specific site:
Access-Control-Allow-Origin: https://mysite.com

If the response does not satisfy the CORS rules, browser JavaScript is prevented from reading the response and you may see an error like:

text

Access to fetch at 'https://api.someothersite.com/data'
from origin 'https://mysite.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

http

OPTIONS /api/users HTTP/1.1
Origin: https://mysite.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization

http

Access-Control-Allow-Origin: https://mysite.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization

The browser may send the request to the server, but if the response does not satisfy the CORS rules, browser JavaScript is prevented from reading that response. The server may have received and processed the request even though your code cannot access the response.

For some cross-origin requests, the browser first sends an HTTP OPTIONS request to check whether the server permits the actual request. This is called a preflight request. The server responds with CORS headers describing the allowed origin, methods, and headers. If permitted, the browser sends the actual request.

  • CORS is a browser security feature - it doesn't affect server-to-server requests
  • If you control the API, CORS is usually configured on the server by returning the appropriate response headers
  • If you don't control the API, you may need a server-side proxy or another architecture that avoids the browser cross-origin restriction
  • Access-Control-Allow-Origin: * allows browser JavaScript from any origin to access eligible responses for requests that satisfy CORS. CORS is not authentication or API access control.

When a cross-origin request includes credentials such as cookies, the server must explicitly allow the requesting origin and return Access-Control-Allow-Credentials: true. A wildcard origin (*) cannot be used for credentialed CORS responses.

Quick tip: CORS is a browser security mechanism, so tools such as Postman do not enforce browser CORS restrictions.

See how a server grants cross-origin browser access.

Reuse a cached response
Freshness and validation avoid extra downloads.
Fresh response: Reuse it without contacting the server.
Stale response with an ETag: Ask whether the cached version is still valid.
304 Not Modified: Reuse the cached body. A 200 brings a new one.
// Browser sends:
If-None-Match: "assets-v3"
// Server replies if unchanged:
HTTP/1.1 304 Not Modified
Revalidation uses the network but can skip the body.

A browser cache stores reusable responses such as images, CSS, JavaScript, and API data. On a later visit, the browser can reuse a fresh response instead of downloading it again, which reduces waiting and network work.

Servers control caching with headers:

http

Cache-Control: public, max-age=31536000, immutable
ETag: "assets-v3"

// For data that must be checked frequently:
Cache-Control: no-cache

max-age tells the browser how long a response can be reused. An ETag lets the browser ask whether a cached response changed. no-cache means the browser may store the response but should validate it before reuse; it does not necessarily mean “do not store anything.”

A beginner performance check

  1. Open DevTools and choose the Network panel. Reload with the panel open.
  2. Check the Size, Time, status, and Waterfall for the largest or slowest resources.
  3. Reload again and look for from memory cache or from disk cache.
  4. Use the Performance panel for long JavaScript tasks and the Lighthouse panel for page-load opportunities.
  5. Improve one bottleneck: compress or resize images, defer non-critical scripts, reduce requests, or set appropriate cache headers. Measure again.
Common browser-performance bottlenecks and first actions.
Symptom Inspect Possible first improvement
Large initial download Network resource size and transfer time Compress media, split code, and defer features not needed at startup.
Slow first visual result Waterfall and Lighthouse LCP opportunities Prioritize the main image and critical CSS; avoid blocking scripts.
Page feels unresponsive Performance panel Main track and long tasks Reduce JavaScript work, batch DOM changes, or move CPU-heavy work to a worker.
Common Cache-Control directives
DirectiveMeaning
max-age=3600Response can be reused as fresh for 3600 seconds
no-cacheResponse must be validated before reuse
no-storeDo not store the response in caches
publicResponse may be stored by shared caches
privateResponse is intended for a private cache

http

// Initial response
HTTP/1.1 200 OK
ETag: "version-1"

// Later request
If-None-Match: "version-1"

// If unchanged
HTTP/1.1 304 Not Modified

A 304 Not Modified response tells the browser it can reuse its cached copy.

Important: caching improves repeat visits, but stale data and cache invalidation are application decisions. Version static filenames or query strings when you need browsers to fetch a new asset.
  • The browser acts as a client and communicates with servers.
  • Requests have a method (GET, POST, PUT, DELETE), a URL, headers, and optionally a body.
  • Responses have a status code (200, 404, 500, etc.), headers, and a body with the data.
  • An API is a way for two applications to communicate - it exposes endpoints you can call to get or send data.
  • REST is an architectural style for networked APIs: use URLs to represent resources, HTTP methods to communicate intended actions, stateless requests, and representations such as JSON.
  • CORS is a browser security mechanism that controls whether JavaScript can access responses from another origin based on the server's CORS headers.
  • CORS errors are enforced by the browser. If you control the API, configure the appropriate CORS policy on the server.
  • HTTPS uses TLS to protect confidentiality, integrity, and domain authentication during HTTP communication.
  • Caching lets browsers reuse responses. Use Network, Performance, and Lighthouse panels to find download and rendering bottlenecks.
  • DNS translates domain names into IP addresses.
What's next? Now that you know how the web works, explore Fetch API to start making real HTTP requests from JavaScript.

Reviewed by

SimplyJavaScript Editorial Team

Technical editors and JavaScript educators with hands-on experience building frontend projects, writing learning material, and reviewing tutorials for clarity, accuracy, and beginner-friendly guidance.