Skip to main content
Express.js Tutorial
CHAPTER 05 Beginner

Express Routing Basics

Updated: May 14, 2026
25 min read

# CHAPTER 5

Express Routing Basics

1. Introduction

A web server is useless if it only has one page. Modern applications require dozens of endpoints: one to view a profile, one to update a password, and one to delete an account. Routing refers to determining how an application responds to a client request to a particular endpoint. In this chapter, we will master Express routing, covering the core HTTP methods, capturing dynamic data from URLs, and learning how to structure API endpoints.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Map endpoints using GET, POST, PUT, and DELETE methods.
  • Define dynamic route parameters (e.g., /users/:id).
  • Extract data securely from req.params.
  • Handle 404 "Not Found" scenarios for undefined routes.

3. Beginner-Friendly Explanation

Imagine your Express server is an enormous filing cabinet with thousands of drawers. When a user wants a specific file, they cannot just yell "Give me a file!" They must specify the action and the location.
  • Action (HTTP Method): "I want to READ." (GET)
  • Location (The Path): "Drawer named 'Users'." (/users)
Routing is the receptionist standing at the cabinet. When the user says GET /users, the receptionist knows exactly which drawer to open. If the user says DELETE /users, the receptionist knows to throw the drawer in the trash.

4. Basic Routing (The CRUD Verbs)

Express provides methods that perfectly match standard HTTP verbs.
javascript
12345678910111213141516171819202122
const express = require('express');
const app = express();

// READ data
app.get('/api/articles', (req, res) => {
    res.send('Fetching all articles...');
});

// CREATE data
app.post('/api/articles', (req, res) => {
    res.send('Creating a new article...');
});

// UPDATE data
app.put('/api/articles', (req, res) => {
    res.send('Updating the article...');
});

// DELETE data
app.delete('/api/articles', (req, res) => {
    res.send('Deleting the article...');
});

*Notice how the URL path (/api/articles) is exactly the same! The only difference is the HTTP Method. This is the core principle of REST API design.*

5. Dynamic Route Parameters (req.params)

If you want to view the profile of User #42, you do not write a hardcoded route for app.get('/users/42'). You use a Route Parameter by prefixing a word with a colon (:).
javascript
12345678
// The ':id' acts as a wildcard placeholder
app.get('/api/users/:id', (req, res) => {
    
    // We extract the value from the req.params object
    const userId = req.params.id;
    
    res.send(`You requested the profile for user ID: ${userId}`);
});

*If a user visits /api/users/99, the browser will display "You requested the profile for user ID: 99".*

6. Multiple Route Parameters

You can chain multiple dynamic parameters together. For example, finding a specific post by a specific user.
javascript
12345
app.get('/api/users/:userId/posts/:postId', (req, res) => {
    const { userId, postId } = req.params; // ES6 Destructuring
    
    res.send(`Fetching Post #${postId} authored by User #${userId}`);
});

*(URL: /api/users/5/posts/10)*

7. Handling 404 Not Found

Express evaluates routes from top to bottom. If a user visits a URL that does not match *any* of your defined routes, Express hangs or sends a generic error. You can add a "catch-all" route at the very bottom of your file to handle 404 errors gracefully.
javascript
123456789
// Define all your actual routes first...
app.get('/home', ...);
app.get('/about', ...);

// Catch-all 404 Route (MUST be at the bottom)
// The '*' means "match absolutely anything"
app.get('*', (req, res) => {
    res.status(404).send('404 Error: The page you are looking for does not exist.');
});

8. Backend Workflow: API Naming Conventions

When defining routes for an API, professional developers use plural nouns, not verbs.
  • Bad: app.get('/api/get-users')
  • Good: app.get('/api/users')
  • Bad: app.post('/api/create-post')
  • Good: app.post('/api/posts')

9. Best Practices

  • Route Ordering: Because Express reads top-to-bottom, static routes MUST go before dynamic routes. If you place app.get('/users/:id') before app.get('/users/admin'), and a user visits /users/admin, Express will think the word "admin" is a dynamic ID and trigger the wrong route!

10. Common Mistakes

  • Testing POST/PUT/DELETE in a Browser: Beginners often write an app.post('/api/users') route, type that URL into Google Chrome, and get a "Cannot GET /api/users" error. Web browsers can only make GET requests via the address bar. To test POST, PUT, or DELETE routes, you must use HTML Forms or a tool like Postman.

11. Exercises

  1. 1. Explain the architectural benefit of using identical URLs (e.g., /api/products) with different HTTP methods (GET vs POST) rather than writing unique URLs for every action (e.g., /api/get-products and /api/create-product).

12. Coding Challenges

  • Challenge: Write an Express route that handles a DELETE request for a specific product. The URL should utilize a dynamic parameter for the product ID. Inside the route, use res.send() to return a message confirming the deletion of that specific ID.

13. MCQs with Answers

Question 1

Which object in Express holds the dynamic values extracted from the URL path, such as the 42 in /users/42?

Question 2

Why must a "catch-all" 404 route (using *) be placed at the very bottom of the Express route definitions?

14. Interview Questions

  • Q: Explain how Route Parameters (req.params) work in Express. Provide a use case where chaining multiple parameters in a single URL is necessary.
  • Q: Why is the physical ordering of route definitions critical in an Express application, particularly concerning dynamic wildcards versus static endpoints?

15. FAQs

Q: Can a route parameter be optional? A: Yes! You can add a question mark ? after the parameter name. E.g., app.get('/api/users/:id?'). If the user visits /api/users/, the req.params.id will simply be undefined.

16. Summary

In Chapter 5, we mastered traffic direction. We mapped the standard REST HTTP verbs (GET, POST, PUT, DELETE) to specific application logic. We learned how to write dynamic, reusable endpoints using Route Parameters (req.params), allowing a single block of code to handle requests for thousands of different database records. Finally, we learned how to gracefully handle invalid traffic using a catch-all 404 route.

17. Next Chapter Recommendation

We know how to define routes, but so far we are only returning plain text using res.send(). Modern APIs must return formatted data. Proceed to Chapter 6: Handling Requests and Responses.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·