Skip to main content
Node.js Basics
CHAPTER 14 Beginner

Express.js Routing

Updated: May 13, 2026
20 min read

# Express.js Routing

Welcome to Chapter 14! In the previous chapter, we created simple GET routes. But modern web applications do much more than just *get* data. Users submit forms, update their profiles, and delete comments.

To handle these actions, we use different HTTP Methods (Verbs). Additionally, we can't hardcode a route for every single user profile on a website. In this chapter, we will learn about advanced routing, RESTful verbs, and dynamic route parameters.

---

1. Introduction

Routing refers to determining how an application responds to a client request to a particular endpoint. An endpoint consists of a URI (or path) and an HTTP Request Method (GET, POST, etc.).

Express provides methods that correspond perfectly to HTTP verbs:

  • app.get(): Retrieve data.
  • app.post(): Submit/create new data.
  • app.put(): Update existing data.
  • app.delete(): Remove data.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Create routes for different HTTP methods.
  • Differentiate between GET and POST requests.
  • Understand and create dynamic routes using Route Parameters (:id).
  • Extract dynamic data using req.params.
  • Group routes using express.Router() for better organization.

---

3. Beginner-Friendly Explanations

GET vs POST

  • GET is like reading a book. You are asking the server for information. It is safe, and you can bookmark it. (Every time you type a URL in Chrome, it's a GET request).
  • POST is like submitting a test. You are sending data *to* the server to be saved or processed. You cannot simply type a POST URL into a browser; it usually comes from an HTML <form> or an API request.

Dynamic Route Parameters (req.params)

Imagine Facebook. They don't write a route for app.get('/profile/mark') and app.get('/profile/sarah'). They write one Dynamic Route: app.get('/profile/:username'). The colon : tells Express that this part of the URL is a variable placeholder.

---

4. Syntax Explanation

Let's look at how to capture data from a dynamic route.

``javascript id="ch14-syntax-1" const express = require('express'); const app = express();

// The colon ':' creates a parameter named 'userId' app.get('/users/:userId', (req, res) => { // We access the value using req.params const requestedId = req.params.userId; res.send(<h1>Viewing profile for User ID: ${requestedId}</h1>`); });

app.listen(3000);

1234567891011121314151617181920
**Output Explanation:**
If you visit `http://localhost:3000/users/99`, the browser will display "Viewing profile for User ID: 99". The `req.params` object automatically captured `99` and assigned it to the `userId` key.

---

## 5. Real-world Examples

**E-commerce Product Pages:**
When you shop on Amazon, you might see URLs like `/product/B08N5WRWNW`. Amazon's backend uses a route similar to `app.get('/product/:productId', ...)`.
1. The server extracts `B08N5WRWNW` from `req.params.productId`.
2. It queries the database for that specific ID.
3. It sends back the HTML page populated with that product's title and price.

---

## 6. Multiple Code Examples

### Example 1: Multiple Route Parameters
You can have as many parameters in a URL as you need.

javascript id="ch14-code-1" // Example URL: /flights/JFK/to/LAX app.get('/flights/:from/to/:to', (req, res) => { const departure = req.params.from; const arrival = req.params.to; res.send(Searching flights from ${departure} to ${arrival}...); });

123
### Example 2: Different HTTP Methods
You can have the *exact same URL path*, but different methods. Express is smart enough to know which one to trigger.

javascript id="ch14-code-2" // When user VISITS the page (GET) app.get('/login', (req, res) => { res.send('Please fill out the login form.'); });

// When user SUBMITS the form (POST) app.post('/login', (req, res) => { // (We will learn how to extract form data in Chapter 19) res.send('Login submitted! Verifying credentials...'); });

1234
### Example 3: Using `express.Router()`
If you have 50 routes, `app.js` gets too large. You can split routes into separate files using the Router.

Create a file `routes/blog.js`:

javascript id="ch14-code-3" const express = require('express'); const router = express.Router(); // Create a mini-app

// These routes are relative to where they are mounted router.get('/', (req, res) => res.send('Blog Home')); router.get('/:id', (req, res) => res.send(Reading article ${req.params.id}));

module.exports = router;

1
In your main `app.js`:

javascript id="ch14-code-4" const express = require('express'); const app = express();

const blogRoutes = require('./routes/blog');

// Mount the router! All routes inside blog.js now start with /blog app.use('/blog', blogRoutes);

app.listen(3000);

12345678910111213141516171819202122232425262728293031323334353637383940
---

## 7. Output Explanations

Using `app.use('/blog', blogRoutes)` is incredibly powerful. Inside `blog.js`, the route is just `router.get('/:id')`. But because it is mounted at `/blog`, the actual URL the user must visit is `http://localhost:3000/blog/5`. This keeps code modular and clean.

---

## 8. Common Mistakes

1. **Route Ordering:** Dynamic routes must go *below* static routes.
   ```javascript
   app.get('/users/:id', ...); // Catches everything!
   app.get('/users/admin', ...); // Will NEVER run, because 'admin' is treated as an :id
   ```
   **Fix:** Put `/users/admin` above `/users/:id`.
2. **Missing Colons:** Writing `app.get('/users/id')` instead of `:id`. This makes it a static route, meaning it will only trigger if the user literally types the letters "i" and "d" in the URL.
3. **Data Types in params:** Everything inside `req.params` is a **String**. If you visit `/users/5`, `req.params.id` is `"5"`. If you need to do math with it, you must use `parseInt()`.

---

## 9. Best Practices

- **RESTful Naming:** Follow REST standards. Use plural nouns for resources. Use `/users` not `/user`. Use `/users/:id` not `/users/getuserbyid/:id`.
- **Use the Router:** As soon as your app has more than 5-10 routes, immediately create a `routes` folder and use `express.Router()`. It will save you massive headaches later.

---

## 10. Exercises

1. Create a route `/math/add/:num1/:num2`. Extract the numbers, add them, and send the result. (Remember to convert the strings to numbers!).
2. Create a route `/color/:choice`. If choice is 'red', send "You chose red". If choice is 'blue', send "You chose blue". If neither, send "Unknown color".

---

## 11. Mini Project: Blog routes system

**Objective:** Build a modular routing system for a blog using `express.Router()`.

**Step 1:** Create `app.js`

javascript id="ch14-mini-project-1" // app.js const express = require('express'); const app = express();

const articleRoutes = require('./routes/articles');

app.get('/', (req, res) => res.send("Welcome to the homepage!"));

// Mount the router app.use('/articles', articleRoutes);

app.listen(3000, () => console.log('Server running...'));

1
**Step 2:** Create `routes/articles.js`

javascript id="ch14-mini-project-2" // routes/articles.js const express = require('express'); const router = express.Router();

// Route: GET /articles router.get('/', (req, res) => { res.send("Here is a list of all articles."); });

// Route: POST /articles (Imagine a form submission) router.post('/', (req, res) => { res.send("New article created!"); });

// Route: GET /articles/:id router.get('/:id', (req, res) => { const articleId = req.params.id; res.send(Reading article with ID: ${articleId}); });

// Route: DELETE /articles/:id router.delete('/:id', (req, res) => { res.send(Article ${req.params.id} has been deleted.); });

module.exports = router;

123456789
*(Note: To test POST and DELETE routes without a frontend, developers usually use a tool like **Postman** or **Insomnia**. For now, just understand the syntax).*

---

## 12. Coding Challenges

**Challenge 1:** Create a route `/search`. Instead of route parameters, look up how to use **Query Parameters** in Express (`req.query`). Make the route respond to `http://localhost:3000/search?keyword=node`.

**Challenge 2:** Fix this routing bug:

javascript router.get('/:username', (req, res) => res.send("Profile")); router.get('/settings', (req, res) => res.send("Settings")); `` Why does visiting /settings show the "Profile" page? Rearrange the code to fix it.

---

13. MCQs with Answers

Q1: How do you define a dynamic route parameter in Express? A) By wrapping it in brackets [id] B) By using a colon :id C) By using a dollar sign $id D) By using a question mark ?id Answer: B

Q2: Which Express object holds the dynamic variables extracted from the URL? A) req.params B) req.query C) req.body D) res.data Answer: A

Q3: Which HTTP method is typically used to create new data? A) GET B) POST C) PUT D) DELETE Answer: B

Q4: What is express.Router() used for? A) To connect to the internet. B) To group routes together in separate files to keep code organized. C) To handle 404 errors automatically. D) To serve static images. Answer: B

---

14. Interview Questions

  1. 1. What is a RESTful API?
*Answer:* REST (Representational State Transfer) is an architectural style for APIs. It relies on standard HTTP methods (GET, POST, PUT, DELETE) and uses predictable, resource-based URLs (like
/users and /users/:id) to perform CRUD operations.
  1. 2. Explain the difference between req.params and req.query.
*Answer:* req.params extracts data from dynamic route paths defined with a colon (e.g., /users/:id). req.query extracts data from the URL query string after a question mark (e.g., /search?name=alice).

---

15. FAQs

Q: How do I test POST or DELETE routes if my browser only does GET requests? A: Backend developers use specialized software like Postman, Insomnia, or the VS Code extension Thunder Client. These tools allow you to construct and send any type of HTTP request to your server to test it.

Q: Is it safe to put database IDs in the URL? A: Yes! IDs like /users/5 or /product/a2b4 are perfectly safe. However, you should never put sensitive data like passwords or social security numbers in the URL!

---

16. Summary

  • GET, POST, PUT, DELETE are standard HTTP methods handled easily by Express.
  • Use a colon : to create dynamic route placeholders.
  • Access dynamic data using req.params.
  • The order of routes matters! Static routes must go before dynamic catch-alls.
  • Use express.Router()` to split large routing files into smaller, modular files.

---

17. Next Chapter Recommendation

We've mastered routes, but what if we want to run a piece of code *before* the route executes? For example, checking if a user is logged in before allowing them to see a profile? This brings us to the most powerful concept in Express. In Chapter 15: Express.js Middleware, we will learn how to intercept requests!

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: ·