Learn Express.js Β· 2/14

Routing Fundamentals: Directing Traffic

7 min read

Imagine you are running a giant automated drive-thru restaurant. Customers pull up to different windows, shouting out requests: some want to look at the menu, some want to place an order, and some want to change the order they just placed. If your restaurant does not have a system to figure out what the customer wants and where that request should go, chaos ensues.

In Express.js, Routing is the system that determines how an application responds to a client request to a particular endpoint. An endpoint consists of a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Before we direct traffic, let us set up the industry-standard Express boilerplate.

Prerequisites & Setup:
Create a new folder, open your terminal, and run the following:

bash
npm init -y
npm install express

Create a file named server.js:

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

// Industry Standard: We need this middleware to read JSON data sent in requests!
app.use(express.json()); 

app.listen(PORT, () => {
  console.log(`Drive-thru is open on port ${PORT} πŸ”`);
});

1. Basic Routing & HTTP Methods (GET, POST, PUT, DELETE) πŸ›£οΈ

The Problem:
When a client application (like a web browser or mobile app) connects to your server, it needs a way to communicate its intent. If a user visits /orders, are they trying to view their orders, create a new order, or cancel an order? Without standardized methods, the server cannot distinguish between reading data and destroying data.

The Solution:
HTTP Methods (also known as HTTP Verbs). These are standardized actions that tell your server exactly what the client wants to do with a specific path. Express provides dedicated functions for each of these methods.

The Definition:
Basic routing in Express connects a specific HTTP method and a specific URL path to a callback handler function. The handler function executes only when both the path and the method match the incoming request.

Here are the four heavyweights of the industry (often referred to as CRUD: Create, Read, Update, Delete):

  1. GET (Read): Asks the server to retrieve a resource. It should never modify data.
  2. POST (Create): Submits new data to the server to create a resource.
  3. PUT (Update): Replaces an existing resource entirely with updated data.
  4. DELETE (Delete): Removes a resource from the server.

Industry Standard Practice

In the professional world, we strictly follow RESTful naming conventions. We use nouns for our paths (e.g., /orders) and rely on the HTTP methods to define the action. We do not write paths like /getOrders or /createOrder.

javascript
// 🟒 GET: Fetching data
app.get('/api/orders', (req, res) => {
  res.status(200).json({ message: "Here are all your orders!" });
});

// 🟑 POST: Creating new data
app.post('/api/orders', (req, res) => {
  // req.body contains the incoming JSON data (thanks to express.json())
  const newOrder = req.body; 
  res.status(201).json({ message: "New order created!", data: newOrder });
});

// 🟠 PUT: Updating existing data
app.put('/api/orders', (req, res) => {
  res.status(200).json({ message: "Order completely updated!" });
});

// πŸ”΄ DELETE: Destroying data
app.delete('/api/orders', (req, res) => {
  res.status(200).json({ message: "Order deleted successfully." });
});

Under the hood: When a request arrives, Express cycles through your code from top to bottom. It checks the HTTP method and the path. When it finds an exact match, it executes the callback function provided.


2. Dynamic Routing: Extracting Route Parameters 🏷️

The Problem:
Imagine Facebook writing a specific route for every single user. You would have app.get('/users/alice'), app.get('/users/bob'), and so on. If you hardcode routes for 3 billion users, your server.js file will be terabytes in size, and your computer will likely catch fire trying to parse it.

The Solution:
Route Parameters. Instead of hardcoding the exact URL, we define a placeholder variable in the URL path.

The Definition:
Dynamic Routing is a feature that allows developers to define a single route pattern capable of matching multiple URLs. It achieves this by capturing values specified at certain positions in the URL path and storing them in an object called req.params.

To define a route parameter in Express, you prefix a section of the path with a colon :.

javascript
// The ':id' is a dynamic route parameter
app.get('/api/orders/:id', (req, res) => {
  // Extracting the parameter from the request object
  const orderId = req.params.id;
  
  res.status(200).json({ 
    message: `Fetching details for order number ${orderId}` 
  });
});

If a user visits /api/orders/9942, Express intercepts the request, maps 9942 to the id key, and exposes it as req.params.id.

Industry Practicality:
This is universally used for fetching single items, updating specific records, or deleting specific records.

javascript
// Multiple parameters are also common!
app.get('/api/users/:userId/orders/:orderId', (req, res) => {
  const { userId, orderId } = req.params; // Destructuring for cleaner code
  res.status(200).json({ 
    message: `User ${userId} is looking at order ${orderId}` 
  });
});

3. Filtering and Searching: Handling Query Strings πŸ”

The Problem:
You have a database with 5 million pizza orders. A client application makes a GET request to /api/orders. If your server tries to send 5 million records back at once, your database will crash, the server will run out of memory, and the client's browser will freeze. The client needs a way to say, "I only want orders from today, and I only want page 1."

We could use route parameters like /api/orders/today/1, but this violates REST standards because "today" and "1" are not unique resource identifiers; they are search filters.

The Solution:
Query Strings.

The Definition:
A query string is a part of a URL that assigns values to specified parameters. It begins after a question mark ? and consists of key-value pairs separated by ampersands &. Express automatically parses these and places them in an object called req.query.

If the client makes a request to: /api/orders?status=delivered&size=large

javascript
app.get('/api/orders', (req, res) => {
  // Extracting filters from the query object
  const { status, size } = req.query;

  // In a real application, you would pass these to your database query
  if (status && size) {
    return res.status(200).json({ 
      message: `Fetching orders that are ${status} and size ${size}` 
    });
  }

  res.status(200).json({ message: "Fetching a default limited list of orders." });
});

Industry Practicality:
Query strings are the absolute standard for Search, Sorting, Filtering, and Pagination.

  • Pagination: /api/products?page=2&limit=50
  • Sorting: /api/products?sort=price_asc
  • Searching: /api/products?search=spicy

Note: Notice how we used return in the if block above. Express does not automatically stop executing your code after sending a response. If you don't return, Express will try to send a second response below it, which triggers the infamous Cannot set headers after they are sent to the client error.


4. Handling 404s: The Catch-All Route πŸͺ€

The Problem:
Users type things wrong. They might visit /api/oders instead of /api/orders. By default, Express responds to an unmatched route with a plain, ugly HTML page saying Cannot GET /api/oders. If you are building a professional API that speaks JSON, sending back an HTML error page will crash the frontend application that is trying to parse JSON.

The Solution:
The Catch-All Route.

The Definition:
A catch-all route is a piece of Express middleware designed to intercept any incoming request that has not been matched by any preceding route definitions.

Because Express evaluates routes sequentially from top to bottom, if a request makes it all the way to the bottom of your file without matching a app.get(), app.post(), or dynamic route, it means the route does not exist.

We handle this by placing a wildcard route or a generic middleware function at the very end of our route definitions, right before app.listen().

javascript
// ... all your other routes go above here

// πŸ›‘ The Catch-All 404 Handler
app.use((req, res) => {
  // We explicitly set the HTTP status code to 404 (Not Found)
  res.status(404).json({
    error: {
      message: "Resource not found!",
      path_attempted: req.originalUrl
    }
  });
});

app.listen(PORT, () => {
  console.log(`Server running...`);
});

Industry Practicality:
Always explicitly define your 404 behavior. Using app.use() at the bottom is preferred over app.get('*') because app.use() catches all HTTP methods (GET, POST, PUT, DELETE), ensuring that a rogue POST request to a non-existent endpoint is also handled gracefully.


References & Extra Reading πŸ“š

Challenge

Challenge: Build a Product Inventory REST API

Your task is to create a complete Express.js server that provides a RESTful API for managing a product inventory. You must implement all standard CRUD operations and handle requests for both collections and specific items, including filtering and error handling.

Requirements:

  1. Server Setup: Initialize the Express server to listen on the provided PORT. You must include the necessary middleware to parse incoming JSON request bodies.

  2. GET /api/products: Create a route to fetch products.

    • By default, it should return the entire list of products.
    • It must support optional query string filtering. If a category query parameter is provided (e.g., /api/products?category=Electronics), it should return only the products matching that category.
    • It must also support an inStock query parameter. If inStock=true, it should return only products that are in stock.
    • Both filters should be able to work independently or together.
  3. POST /api/products: Create a route to add a new product to the inventory. The new product data will be in the request body. Respond with a 201 status code and the newly created product object.

  4. GET /api/products/:id: Create a dynamic route to fetch a single product by its id. If a product with the given id is not found, respond with a 404 status and a JSON error message { "error": "Product not found" }.

  5. PUT /api/products/:id: Create a dynamic route to update an existing product's information using its id. The update data will be in the request body. Respond with the updated product object. If the product is not found, respond with a 404 status and the same error message as the previous requirement.

  6. DELETE /api/products/:id: Create a dynamic route to remove a product from the inventory by its id. Respond with a success message. If the product is not found, respond with a 404 status and the same error message.

  7. 404 Catch-All: Implement a final catch-all route that responds to any request that does not match the defined routes. It must respond with a 404 status and a JSON object: { "error": "Route not found" }.

Expected result

Your final code should be a single script that correctly sets up an Express server and defines all the required routes and middleware.

  • The express.json() middleware must be correctly implemented at the top.
  • A GET route for /api/products should be defined, which conditionally filters the products array based on the req.query object for category and inStock.
  • A POST route for /api/products must be implemented to add a new item to the products array using data from req.body.
  • Three dynamic routes, GET, PUT, and DELETE for /api/products/:id, must be defined. They should correctly parse the id from req.params and perform the corresponding find, update, or remove operation on the products array.
  • The dynamic routes must handle cases where the id does not exist by returning a 404 status with a JSON error object.
  • The last piece of routing logic must be a catch-all app.use() handler that sends a 404 status and a JSON error message for any unmatched routes.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.