1.5 Hours

7. Initializing Your First Server with Express/Flask

First Server

A server is not a physical machine — it's a software program. More specifically, it is an application that runs in an infinite loop, permanently listening on a specific network port for incoming connections. When a connection arrives carrying an HTTP request, it wakes up, executes logic, sends a response, and goes back to listening.

In this module, we build a working server in both JavaScript (Node.js with Express) and Python (Flask), explaining every single line of code.

IP Addresses & Ports — Where Does the Traffic Go?

Every computer on a network is identified by an IP Address — a unique numeric label like 192.168.1.105 or the public address 104.21.8.3. But a computer can run hundreds of programs simultaneously. How does incoming traffic know which program to go to? That's the job of Ports.

A port is a numbered door (0–65535) on a computer. Each running program listens on a unique port. Think of the IP address as the building's street address, and the port as the specific apartment number inside that building.

Port 80

Standard HTTP traffic. When you browse a non-HTTPS site, your browser connects to port 80 by default.

Port 443

Standard HTTPS traffic. All encrypted web traffic goes through port 443.

Port 3000 / 8000

Common conventions for local development servers. Not special — just popular choices that developers agree on by habit.

Port 5432 / 3306

PostgreSQL listens on 5432. MySQL listens on 3306 by default.

localhost and 127.0.0.1: When developing on your own machine, localhost and 127.0.0.1 are aliases that mean this computer, right here. A request to http://localhost:3000 stays entirely inside your machine — no internet connection needed.

Setting Up a Node.js + Express Server

Before writing any server code, you need Node.js installed. Verify your installation by running both commands in your terminal:

Bash
node --version
npm --version

Now create a fresh project folder and initialize it:

Bash
mkdir my-first-server
cd my-first-server
npm init -y
npm install express

Create a file called server.js and add the following code:

JavaScript
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

app.get('/ping', (req, res) => {
    res.status(200).json({
        message: 'Pong!',
        timestamp: new Date().toISOString(),
        status: 'Server is alive and running'
    });
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
    console.log(`   Try visiting http://localhost:${PORT}/ping in your browser`);
});

Run your server:

Bash
node server.js

Now open your browser to http://localhost:3000/ping. You'll see the JSON response! You have just built a working server.

What Just Happened? The Event Loop.

Notice that when you run node server.js, the terminal doesn't return to the command prompt like a normal script would. It stays open, printing that one line. This is because app.listen() enters Node.js's Event Loop.

Node.js is single-threaded. Instead of creating a new thread for every incoming request (which is how Java/Apache works), it uses a single thread with an event loop that efficiently handles thousands of simultaneous connections by pausing and resuming work as needed. When a request arrives, Node puts it in the event queue, processes it when ready, and goes back to waiting.

To stop your server: Press Ctrl + C in the terminal. This sends an interrupt signal that terminates the process.

Building a Server in Python (Flask)

If you prefer Python, Flask is a lightweight micro-framework that produces a nearly identical mental model to Express. First, install it:

Bash
pip install flask

Create a file called server.py:

Python 3
from flask import Flask, jsonify
from datetime import datetime
import os

app = Flask(__name__)

@app.route('/ping', methods=['GET'])
def ping():
    return jsonify({
        'message': 'Pong!',
        'timestamp': datetime.utcnow().isoformat(),
        'status': 'Server is alive and running'
    }), 200

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 8000))
    app.run(host='0.0.0.0', port=port, debug=True)

Run it:

Bash
python server.py

Handling Multiple Routes

A real server has dozens or hundreds of routes. Here is how you add more:

JavaScript
const express = require('express');
const app = express();

app.use(express.json());

const users = [
    { id: 1, name: 'Ama',   role: 'admin' },
    { id: 2, name: 'Kofi',  role: 'user' },
    { id: 3, name: 'Abena', role: 'user' }
];

app.get('/', (req, res) => {
    res.json({ message: 'Welcome to the VoidX API', version: '1.0.0' });
});

app.get('/users', (req, res) => {
    res.json({ count: users.length, users });
});

app.get('/users/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const user = users.find(u => u.id === id);
    if (!user) {
        return res.status(404).json({ error: `User with id ${id} not found` });
    }
    res.status(200).json(user);
});

app.post('/users', (req, res) => {
    const { name, role } = req.body;
    if (!name) {
        return res.status(400).json({ error: 'Name is required' });
    }
    const newUser = {
        id: users.length + 1,
        name,
        role: role || 'user'
    };
    users.push(newUser);
    res.status(201).json({ message: 'User created', user: newUser });
});

app.listen(3000, () => console.log('Server running on port 3000'));
Port Already in Use Error:

If you see Error: listen EADDRINUSE: address already in use :::3000, another process is already using that port. Either change your port number in the code, or find and kill the existing process. On Mac/Linux: lsof -i :3000 then kill -9 [PID].

Nodemon — Auto-Restart on Save

Right now, every time you edit your server code, you have to manually Ctrl+C and restart. During development, this becomes exhausting within minutes. Nodemon is a tool that watches your files and automatically restarts the server whenever you save a change.

Bash
npm install --save-dev nodemon
npx nodemon server.js

Add a script to your package.json so you can just run npm run dev:

Text
{
  "scripts": {
    "start": "node server.js",
    "dev":   "nodemon server.js"
  }
}

Knowledge Check

Ready to test your understanding of 7. Initializing Your First Server with Express/Flask?

Back