Learn Node.js · 6/13

Express.js: The De Facto Node Web Framework

10 min read

Welcome, future backend wizard! So, you've dipped your toes into the world of Node.js. You've seen that you can create a server with the built-in http module. You might have also noticed it's a bit... verbose. It's like being given a pile of car parts and told, "Go on, build a Ferrari." It's possible, but you'll spend a lot of time just building the wrench.

The Problem: Building a web server from scratch with just Node.js is powerful but complex. You have to manually parse URLs, handle different HTTP methods for the same route, and manage the request-response cycle in a very low-level way. It's not ideal for building applications quickly and efficiently.

The Solution: Enter Express.js! Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It's the friendly mechanic who hands you a pre-built chassis, a powerful engine, and a well-organized toolbox, letting you focus on the cool parts of building your car, not on forging the metal.


1. Why Express? Installation and Basic Server Setup ⚙️

Express simplifies the process of creating a server and handling web requests. It provides a thin layer of fundamental web application features without obscuring the Node.js features you know and love. Let's see it in action.

Installation

Getting started is a breeze. First, you'll need a project folder. Let's make one.

  1. Create a project directory:

    bash
    mkdir my-awesome-app
    cd my-awesome-app
  2. Initialize a Node.js project: This creates a package.json file, which is like the birth certificate for your project. It tracks your project's details and dependencies.

    bash
    npm init -y

    The -y flag just says "yes" to all the default questions. We're in a hurry to build cool stuff!

  3. Install Express: This is the magic command. It downloads Express and adds it to your project's dependencies.

    bash
    npm install express

That's it! You're ready to build a server.

Your First Express Server: "Hello, World!"

Create a file named app.js (or index.js, your choice!) and add the following code. This is the traditional "Hello, World!" that programmers have been using to start their journeys for decades.

javascript
// 1. Import Express
const express = require('express');

// 2. Create an Express application instance
const app = express();

// 3. Define a port for the server to listen on
const port = 3000;

// 4. Define a route for the root URL ('/')
// This tells the server what to do when someone visits your homepage
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 5. Start the server and listen for incoming requests
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Let's break it down:

  • require('express'): We import the Express module we just installed.
  • const app = express(): We create an instance of an Express application. This app object is the core of your server.
  • app.get('/', ...): This is a route handler. It tells the app to listen for GET requests at the root URL (/). When it gets one, it executes the callback function.
  • (req, res): The callback function receives two important objects: req (the request) and res (the response). req holds all the information about the incoming request, and res is what we use to send a response back to the client.
  • res.send(...): This is an Express-specific method that sends a response back to the browser. It's much simpler than the res.end() you might have used with the http module.
  • app.listen(...): This starts up the server on the specified port and makes it ready to accept requests.

To run your server, open your terminal in the project folder and type:

bash
node app.js

Now, open your web browser and navigate to http://localhost:3000. You should see "Hello World!" on the page. You've just built a web server in a handful of lines. That's the power of Express!


2. Routing Fundamentals: Handling GET, POST, PUT, DELETE 🛣️

The Problem: A website isn't just one page. You have a homepage, an "about" page, a "contact" page, an API to get user data, another to create new data, and so on. How do you tell your server to do different things for different URLs and different HTTP methods?

The Solution: Routing. Routing refers to how an application responds to a client request to a specific endpoint, which is a combination of a URI (a path) and an HTTP request method (like GET, POST, etc.).

Imagine you're the manager of a large warehouse. You receive orders (requests) all day. An order might be to:

  • GET an item from a shelf (Fetch data).
  • POST a new item to be stored on a shelf (Create data).
  • PUT an existing item in a new location (Update data).
  • DELETE an item from the inventory (Delete data).

Express provides simple methods that match these HTTP verbs.

  • app.get(): Handle GET requests.
  • app.post(): Handle POST requests.
  • app.put(): Handle PUT requests.
  • app.delete(): Handle DELETE requests.

Let's expand our app.js to handle a few more routes for a hypothetical to-do list application.

javascript
const express = require('express');
const app = express();
const port = 3000;

// GET request to the homepage
app.get('/', (req, res) => {
  res.send('Welcome to our To-Do List API!');
});

// GET request to fetch all to-dos
app.get('/todos', (req, res) => {
  // In a real app, you'd fetch this from a database
  const todos = [
    { id: 1, task: 'Learn Express', completed: true },
    { id: 2, task: 'Build a server', completed: false }
  ];
  res.json(todos); // res.json sends a JSON response
});

// POST request to create a new to-do
app.post('/todos', (req, res) => {
  // In a real app, you'd save the new to-do to a database
  console.log('Received a new to-do!');
  res.status(201).send('To-Do created successfully!');
});

// PUT request to update a to-do
app.put('/todos/1', (req, res) => {
  console.log('Updating to-do with ID 1');
  res.send('To-Do with ID 1 updated!');
});

// DELETE request to delete a to-do
app.delete('/todos/1', (req, res) => {
  console.log('Deleting to-do with ID 1');
  res.send('To-Do with ID 1 deleted!');
});


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

Now your server can handle different requests at different endpoints, making it much more useful than a simple "Hello World" page.


3. Extracting Data: Params, Queries, and Body Payloads 📦

The Problem: Our routes are static. The PUT and DELETE routes always affect the to-do with ID 1. That's not very dynamic! How do we handle requests for /todos/2, /todos/42, or a search like /todos?completed=true? And how do we actually get the data for a new to-do in our POST request?

The Solution: Express gives us easy ways to access data sent from the client through the req object. The three main ways are req.params, req.query, and req.body.

req.params (Route Parameters)

Route parameters are used to capture values from named sections of the URL. Think of them as wildcards in your route path. You define them with a colon (:).

Use Case: When you need to identify a specific resource. For example, getting a user by their ID.

javascript
// Route with a parameter for the to-do ID
app.get('/todos/:id', (req, res) => {
  const userId = req.params.id;
  // Now you can use userId to find the specific to-do in your database
  res.send(`Fetching details for To-Do #${userId}`);
});

If a user navigates to http://localhost:3000/todos/42, req.params.id will be "42".

req.query (Query Strings)

Query strings are the key-value pairs at the end of a URL, starting with a ?. They are typically used for filtering, sorting, or pagination.

Use Case: When you want to filter a list of resources. For example, finding all completed to-dos or searching for a specific task.

javascript
// Route that uses a query string
app.get('/search', (req, res) => {
  const searchTerm = req.query.q; // for a URL like /search?q=express
  const filterBy = req.query.filter; // for a URL like /search?q=tasks&filter=completed

  res.send(`Searching for "${searchTerm}" with filter "${filterBy}"`);
});

If a user goes to http://localhost:3000/search?q=learning&filter=urgent, req.query will be { q: 'learning', filter: 'urgent' }.

req.body (Request Body)

The request body is where clients send complex data, usually in JSON format, for POST and PUT requests. Imagine a user filling out a registration form; all that information (name, email, password) is sent in the request body.

The Catch: By default, Express doesn't know how to read the request body. It's like receiving a package but not having a box cutter. We need a tool—a middleware—to parse this data for us.

For modern Express (version 4.16.0+), the tool is built-in!

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

// Middleware to parse JSON bodies
app.use(express.json());
// Middleware to parse URL-encoded bodies (from HTML forms)
app.use(express.urlencoded({ extended: true }));

app.post('/todos', (req, res) => {
  const newTodo = req.body;
  console.log('New To-Do Data:', newTodo);
  // Example: newTodo could be { "task": "Master Express", "priority": "high" }
  res.status(201).send(`Created a new to-do: "${newTodo.task}"`);
});

// ... other routes and app.listen

Now when you send a POST request to /todos with a JSON payload, req.body will contain the parsed data, ready for you to use.


4. The Magic of Middleware: Express Architecture 🧩

The Problem: Many of our routes might need to perform the same preliminary checks. For example:

  • Log the time of every request.
  • Check if a user is authenticated before they can access certain routes.
  • Parse incoming JSON data (like we just did!).

Copying and pasting this logic into every single route handler would be a disaster. It's repetitive, hard to maintain, and a violation of the DRY (Don't Repeat Yourself) principle.

The Solution: Middleware! Middleware functions are the heart and soul of Express. An Express application is essentially a series of middleware function calls.

A middleware is simply a function that has access to the req object, the res object, and the next function in the application’s request-response cycle.

Think of it like an assembly line for requests.

  1. A request comes in.
  2. It goes to the first station (a middleware) which might stamp the time on it.
  3. Then, it calls next() to pass it to the second station.
  4. The second station (another middleware) checks for a security badge.
  5. It calls next() to pass it to its final destination (the route handler).
  6. The route handler processes the request and sends the final product (the response) back.

If a middleware function does not end the request-response cycle (by sending a response), it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging, and the client will time out.

Writing Your Own Middleware

Let's create a simple logger middleware.

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

// A simple logger middleware
const myLogger = (req, res, next) => {
  console.log(`LOGGED: [${req.method}] on URL [${req.url}] at ${new Date()}`);
  next(); // Pass control to the next middleware/route handler
};

// To use this middleware for every request that comes into the app:
app.use(myLogger);

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

app.get('/secret', (req, res) => {
  res.send('You have found the secret page!');
});

// ... app.listen

Now, every time you make a request to any path on your server, you'll see a log message in your console. The order of middleware is crucial; they are executed in the order they are loaded.

Common Third-Party Middleware

The Express ecosystem is vast, with thousands of middleware packages to solve common problems. Here are a few you'll see everywhere:

  • cors: Enables Cross-Origin Resource Sharing, which is necessary when your frontend and backend are on different domains.
  • helmet: Helps secure your app by setting various HTTP headers. It's like putting a safety helmet on your server.
  • morgan: A popular and more powerful HTTP request logger.

To use one, you just install it (npm install cors) and then tell your app to use it (app.use(cors())).


Congratulations! You've journeyed through the fundamentals of Express.js, from setting up a server to handling routes, extracting data, and understanding the power of middleware. You now have the foundational knowledge to build robust and scalable web applications and APIs with Node.js.

📚 Extra Reading & References

Challenge

You are tasked with building a small RESTful API to manage a collection of products using Express.js.

Your API must implement the following features:

  1. Initialize an Express application.
  2. Use the built-in express.json() middleware to handle JSON payloads in request bodies.
  3. Create an in-memory array to store product objects. Each product object should have an id (number), name (string), and category (string).
  4. Implement the following routes:
    • POST /products: This route must accept a JSON object in the request body containing name and category. Your code must generate a unique id for the new product, add it to the in-memory array, and respond with a 201 status code and the newly created product object.
    • GET /products: This route should respond with the entire collection of products. If a query parameter category is provided (e.g., /products?category=electronics), it must filter the collection and return only products matching that category.
    • GET /products/:id: This route must retrieve a product by its id from the route parameters. If a product with the matching id is found, respond with the product object. If no product is found, respond with a 404 status code and a JSON object { "error": "Product not found" }.
  5. Make the server listen on port 3000.

Expected result

Your final code should be a complete Express server script that correctly implements all specified routes and logic.

  • It must import express and initialize an application instance.
  • The express.json() middleware must be applied using app.use() before any route definitions to parse incoming JSON request bodies.
  • The POST /products route handler should:
    • Extract name and category from req.body.
    • Create a new product object with a unique, auto-incrementing id.
    • Push the new product to the products array.
    • Send a 201 status code along with the new product object as the JSON response.
  • The GET /products route handler should:
    • Check for a category property in req.query.
    • If category exists, filter the products array based on the provided category and return the filtered results.
    • If category does not exist, return the entire products array.
  • The GET /products/:id route handler should:
    • Extract the id from req.params and convert it to a number for comparison.
    • Use an appropriate array method like find() to locate the product with the matching id.
    • If the product is found, send it as a JSON response.
    • If the product is not found, send a 404 status with the specified JSON error message.
  • Finally, app.listen() must be called to start the server.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.