Episode 3 — NodeJS MongoDB Backend Architecture / 3.2 — Creating Server

3.2.a — What is a Server

A server is a program that listens for incoming requests over a network and sends back appropriate responses.

Navigation: ← 3.2 Overview | Next → 3.2.b First Node.js Server with HTTP


1. The Simplest Definition

Think of a server like a restaurant kitchen. You (the client) place an order (a request). The kitchen (the server) receives your order, prepares the food, and delivers it to your table (the response). The kitchen does not decide what to cook on its own — it only responds to orders.

In technical terms:

  • A server is a software program that waits for requests and sends back data.
  • A client is any program that sends a request to a server (a browser, a mobile app, another server, a CLI tool like curl).
Client (Browser)  --->  REQUEST  --->  Server (Node.js)
Client (Browser)  <---  RESPONSE <---  Server (Node.js)

2. The Client-Server Model

The client-server model is the foundational architecture of the internet.

┌─────────────┐         ┌─────────────┐
│   CLIENT    │         │   SERVER    │
│             │         │             │
│  Browser    │ ──────> │  Node.js    │
│  Mobile App │ Request │  Python     │
│  Postman    │         │  Java       │
│  curl       │ <────── │  Go         │
│             │ Response│             │
└─────────────┘         └─────────────┘

How it works step by step

  1. The client initiates communication by sending a request.
  2. The server receives the request and processes it.
  3. The server sends back a response (data, HTML, JSON, an image, an error, etc.).
  4. The connection may close or stay open depending on the protocol.

Key characteristics

PropertyClientServer
RoleInitiates requestsResponds to requests
Runs whereUser's deviceRemote machine or localhost
ExamplesChrome, Firefox, mobile appsNode.js, Apache, Nginx
Starts interactionYesNo (it waits)
CountMany clients at onceUsually one server process (with many connections)

3. Physical Server vs Software Server

This distinction confuses many beginners. The word "server" means two different things.

Physical server (hardware)

A physical server is a computer — often a powerful machine sitting in a data center — that runs 24/7. It has a CPU, RAM, storage, and a network connection. Companies like AWS, Google Cloud, and DigitalOcean rent these machines to developers.

Software server (program)

A software server is a program running on a computer that listens for network requests. Your Node.js application is a software server. You can run a software server on your laptop, your phone, or a data center machine.

┌─────────────────────────────────────┐
│  Physical Server (Hardware)          │
│  ┌────────────────────────────────┐ │
│  │  Operating System (Linux)       │ │
│  │  ┌─────────────────────────┐   │ │
│  │  │  Software Server         │   │ │
│  │  │  (Node.js app on :3000)  │   │ │
│  │  └─────────────────────────┘   │ │
│  │  ┌─────────────────────────┐   │ │
│  │  │  Software Server         │   │ │
│  │  │  (Nginx on :80)          │   │ │
│  │  └─────────────────────────┘   │ │
│  └────────────────────────────────┘ │
└─────────────────────────────────────┘

One physical server can run multiple software servers on different ports.


4. How the Internet Reaches Your Server

When a user types https://www.example.com in their browser, an entire chain of events occurs before your server code runs.

Step-by-step journey

User types URL
      │
      ▼
┌─────────────┐
│ DNS Lookup   │  "What IP does example.com point to?"
│              │  Answer: 93.184.216.34
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ TCP Connect  │  Browser connects to 93.184.216.34 on port 443
│              │  (Three-way handshake: SYN → SYN-ACK → ACK)
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ TLS/SSL      │  For HTTPS: encryption is negotiated
│ Handshake    │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ HTTP Request │  Browser sends: GET / HTTP/1.1
│ Sent         │  Host: www.example.com
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ Server       │  Your Node.js code runs!
│ Processes    │  createServer callback fires
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ HTTP Response│  Server sends back HTML, JSON, etc.
│ Sent Back    │
└─────────────┘

DNS — Domain Name System

DNS is like the phonebook of the internet. Humans remember names (google.com), but computers communicate using IP addresses (142.250.80.46).

Browser asks:  "What is the IP of example.com?"
DNS answers:   "93.184.216.34"

IP addresses

An IP address is a unique number that identifies a machine on a network.

VersionFormatExample
IPv4Four numbers (0-255) separated by dots192.168.1.1
IPv6Eight groups of hex digits separated by colons2001:0db8:85a3::8a2e:0370:7334

5. Ports — What They Are and Why They Matter

An IP address identifies a machine. A port identifies a specific program on that machine.

Think of it this way: the IP address is the street address of an apartment building, and the port number is the apartment number.

IP Address:  192.168.1.100     ← which computer
Port:        3000               ← which program on that computer

Full address: 192.168.1.100:3000

Port number range

RangeCategoryNotes
0 - 1023Well-known portsReserved for standard services (HTTP, HTTPS, FTP)
1024 - 49151Registered portsUsed by specific applications (MongoDB, PostgreSQL)
49152 - 65535Dynamic / privateUsed for temporary connections

Common ports every developer should know

PortProtocol / ServiceUsage
20, 21FTPFile transfer
22SSHSecure shell (remote access)
25SMTPEmail sending
53DNSDomain name resolution
80HTTPWeb traffic (unencrypted)
443HTTPSWeb traffic (encrypted)
3000Node.js / React devCommon development port
5173Vite dev serverFrontend build tool
5432PostgreSQLDatabase
6379RedisCache / message broker
8080HTTP AlternativeProxies, development servers
27017MongoDBDatabase

Why port 3000?

There is nothing special about port 3000. It is a convention in the Node.js community. You can use any port above 1023 (ports below 1024 require administrator privileges on most systems).

// All of these are valid
server.listen(3000);  // Convention for Node.js
server.listen(4000);  // Perfectly fine
server.listen(8080);  // Common alternative
server.listen(9999);  // Also fine

6. localhost and 127.0.0.1

When developing, you run your server on your own computer. Instead of using a public IP address, you use localhost.

TermMeaning
localhostA hostname that points to your own machine
127.0.0.1The IPv4 loopback address (same as localhost)
::1The IPv6 loopback address
http://localhost:3000     ← Your browser talks to YOUR machine, port 3000
http://127.0.0.1:3000    ← Identical to the above

Why "loopback"?

The network request "loops back" — it never leaves your computer. The data goes out of your browser's network stack and immediately comes back to the same machine.

Browser ──request──> Network Stack ──loopback──> Your Server
        (never leaves your machine)

This is why no internet connection is needed to develop locally.


7. The Request-Response Cycle in Detail

Every interaction between a client and an HTTP server follows this cycle:

┌──────────────────────────────────────────────────────┐
│                REQUEST-RESPONSE CYCLE                 │
│                                                       │
│  1. Client builds a request                          │
│     - Method (GET, POST, PUT, DELETE)                │
│     - URL (/users, /api/products?page=2)             │
│     - Headers (Content-Type, Authorization)          │
│     - Body (for POST/PUT — JSON, form data)          │
│                                                       │
│  2. Request travels over the network                 │
│     - DNS resolution                                 │
│     - TCP connection                                 │
│     - TLS handshake (if HTTPS)                       │
│                                                       │
│  3. Server receives and processes the request        │
│     - Parses URL, method, headers, body              │
│     - Runs business logic                            │
│     - Queries database if needed                     │
│     - Builds a response                              │
│                                                       │
│  4. Server sends a response                          │
│     - Status code (200, 404, 500)                    │
│     - Headers (Content-Type, Set-Cookie)             │
│     - Body (HTML, JSON, file data)                   │
│                                                       │
│  5. Client receives and processes the response       │
│     - Browser renders HTML                           │
│     - JavaScript processes JSON                      │
│     - Error handling if status >= 400                │
│                                                       │
│  6. Connection closes (or stays open for keep-alive) │
└──────────────────────────────────────────────────────┘

Example: what happens when you visit a website

You type: https://example.com/about

1. Browser sends:
   GET /about HTTP/1.1
   Host: example.com
   Accept: text/html

2. Server receives request, sees URL = "/about"

3. Server reads about.html file from disk

4. Server responds:
   HTTP/1.1 200 OK
   Content-Type: text/html
   Content-Length: 2048

   <html>...about page content...</html>

5. Browser renders the HTML

8. The Stateless Nature of HTTP

HTTP is a stateless protocol. This means each request is independent — the server does not remember previous requests from the same client.

Request 1: GET /login         → Server: "Who are you? Here's a login page."
Request 2: POST /login        → Server: "OK, credentials correct. Here's a token."
Request 3: GET /dashboard     → Server: "Who are you? I don't remember Request 2."

Why stateless?

  • Simplicity: the server does not need to track connections.
  • Scalability: any server in a cluster can handle any request.
  • Reliability: if a server crashes, no session state is lost.

How do we maintain state then?

Since HTTP itself is stateless, developers use workarounds:

MechanismHow it works
CookiesServer sends a Set-Cookie header; browser sends it back on every request
SessionsServer stores state in memory or database, identified by a session ID cookie
Tokens (JWT)Server issues a signed token; client sends it in Authorization header
URL parametersState encoded in the URL (e.g., ?page=2&sort=name)

9. Server-Side vs Client-Side Rendering

Understanding where HTML is generated is fundamental to modern web development.

Server-Side Rendering (SSR)

The server generates the full HTML page and sends it to the browser.

Browser: "GET /about"
Server:  Runs template engine → generates full HTML → sends to browser
Browser: Receives HTML → renders it immediately

Advantages: faster initial load, better SEO, works without JavaScript.

Technologies: EJS, Pug, Handlebars, Next.js (React SSR), Nuxt.js (Vue SSR).

Client-Side Rendering (CSR)

The server sends a minimal HTML file with JavaScript. The JavaScript runs in the browser and builds the page.

Browser: "GET /about"
Server:  Sends minimal HTML + bundle.js
Browser: Loads JavaScript → fetches data via API → renders page

Advantages: rich interactivity, smooth page transitions, reduced server load.

Technologies: React (CRA), Vue, Angular, Svelte.

Comparison

FactorServer-Side RenderingClient-Side Rendering
Initial load speedFaster (HTML is ready)Slower (JS must load first)
SEOExcellentRequires extra work
InteractivityRequires page reloads or hydrationVery interactive
Server loadHigher (generates HTML per request)Lower (serves static files)
ComplexitySimpler for content sitesBetter for app-like interfaces

How this connects to Node.js servers

In this section, we will build servers that handle both patterns:

  • Serving static HTML files (SSR-like).
  • Serving JSON data that a frontend framework fetches (CSR pattern — building APIs).

Key Takeaways

  1. A server is a program that listens for requests and sends responses — nothing more, nothing less.
  2. The client-server model is the foundation of all web communication.
  3. A physical server is hardware; a software server is a program. One machine can run many software servers.
  4. DNS translates domain names to IP addresses; ports identify specific programs on a machine.
  5. localhost (127.0.0.1) is your own machine — requests never leave your computer.
  6. HTTP is stateless: every request is independent, and state is maintained through cookies, sessions, or tokens.
  7. Server-side rendering generates HTML on the server; client-side rendering generates HTML in the browser.

Explain-It Challenge

Scenario: Your non-technical friend asks you, "What actually happens when I type google.com in my browser and press Enter?"

Explain the full journey — from DNS lookup to the page appearing on screen — without using any jargon they would not understand. Use a real-world analogy (postal service, restaurant, library, etc.) to make every step clear.

Write your explanation as if you are texting them. Keep it under 200 words but make sure you cover: DNS, IP address, port, the server processing the request, and the response coming back.


Navigation: ← 3.2 Overview | Next → 3.2.b First Node.js Server with HTTP