From Zero to Hero: Building a Web Server with Node.js and then Express!"

Raheel ParekhRaheel Parekh
4 min read

Creating a web server is one of the fundamental tasks in web development. In this blog post, we will explore how to create a simple web server using Node.js and then enhance it using Express.js. We will also discuss middleware, URL parameters, and query strings, providing a comprehensive understanding of how to handle requests effectively.

Setting Up a Simple Web Server with Node.js

To get started, ensure you have Node.js installed on your machine. You can download it from nodejs.org.

Step 1: Create a Basic Server

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

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, World!\n');
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

Step 2: Run the Server

Run the server using the following command:

node server.js

You can now access your server by navigating to http://localhost:3000 in your web browser.

Creating Routes and Handling Requests with Express

While the raw Node.js server works, Express.js simplifies the process of creating routes and handling requests.

Step 1: Install Express

First, install Express in your project:

npm i express

Step 2: Create an Express Server

Replace the contents of server.js with the following code:

import express from "express";
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

Step 3: Run the Server

Run the server using the following command:

node server.js

You can now access your server by navigating to http://localhost:3000 in your web browser.

Comparison: Raw Node.js vs. Express

FeatureRaw Node.js CodeExpress Code
Server CreationRequires manual handling of HTTP requestsSimplified with app.get() and other methods
Response HandlingRequires setting headers and status codes manuallyBuilt-in methods like res.send()
RoutingRequires custom logic for routingEasy routing with app.get(), app.post(), etc.
Middleware SupportNo built-in middleware supportSupports middleware functions for various tasks
Error HandlingManual error handlingBuilt-in error handling middleware
JSON ParsingRequires manual parsing of JSON bodiesBuilt-in middleware with express.json()
Development SpeedSlower due to manual setupFaster with built-in features and conventions

What is Middleware in Express and How to Use It

Middleware functions are like middlemen in a web application. They sit between the incoming request from a user and the final route handler (controller) that processes that request. Lets understand with this scenario

Scenario:

Imagine you have a web application where users can access certain routes only if they are logged in. Here’s how middleware can help manage this:

  1. Incoming Request: When a user tries to access a protected route (e.g., /dashboard), the request first goes to the middleware.

  2. Middleware Function: The middleware checks if the user is authenticated. If the user is logged in, the middleware allows the request to proceed to the next step (the route handler). If the user is not authenticated, the middleware can redirect them to the login page or send an error response.

     // Sample middleware for authentication
     const authenticateUser = (req, res, next) => {
         if (isAuthenticated) {
             // User is authenticated, proceed to the next middleware or route handler
             next();
         } else {
             // User is not authenticated, send an error response
             res.status(401).send('Unauthorized: Please log in to access this route.');
         }
     };
    
     // Protected route 
     app.get('/dashboard', authenticateUser, (req, res) => {
         res.send('Welcome to your dashboard!');
     });
    

    Explanation of the Example:

    • Middleware Function (authenticateUser):

      • This function checks if the user is authenticated or not with some logic.

      • If the user is authenticated, it calls next(), which passes control to the next middleware or route handler.

      • If the user is not authenticated, it sends a 401 Unauthorized response.

    • Protected Route (/dashboard):

      • When a user tries to access this route, the request first goes through the authenticateUser middleware.

      • Depending on the authentication status, the user will either see the dashboard or receive an error message.

  3. In short , It tells the application, "Hey, before you go to the controller that handles this request, pass through me and let me check if the user is allowed to proceed." This way, middleware helps manage access control and ensures that only authorized users can access specific parts of the application.

Diagram Flow

flowchart TD
    A[User Request to /dashboard] --> B[Middleware: authenticateUser]
    B -->|Authenticated| C[Next Middleware/Route Handler]
    B -->|Not Authenticated| D[Send 401 Unauthorized Response]
    C --> E[Display Dashboard]
0
Subscribe to my newsletter

Read articles from Raheel Parekh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raheel Parekh
Raheel Parekh