Express Routing

Express Routing is a powerful feature of the Express.js framework, a popular web application framework for Node.js. It provides a way to define how your application responds to client requests for specific endpoints, or routes. Routing allows you to map HTTP requests to the corresponding handler functions (controllers), where you define the logic for each request.

1. Basic Routing in Express

In Express, routes are defined by specifying a URL path and the HTTP method (such as GET, POST, PUT, DELETE) that the server should respond to.

Example of Basic Routing:

js
const express = require('express'); const app = express(); // Respond to GET request at root route app.get('/', (req, res) => { res.send('Hello World'); }); // Respond to GET request for a specific route app.get('/about', (req, res) => { res.send('This is the About page'); }); // Start the server app.listen(3000, () => { console.log('Server is running on port 3000'); });
  • GET / responds with “Hello World”
  • GET /about responds with “This is the About page”

2. Route Parameters

Express allows you to define dynamic routes by using route parameters. These parameters are placeholders that match segments of the URL and can be accessed through req.params.

Example:

js
app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID is: ${userId}`); });
  • If you visit /user/123, the response will be User ID is: 123.

You can also define multiple parameters:

js
app.get('/user/:id/:name', (req, res) => { const { id, name } = req.params; res.send(`User ID: ${id}, User Name: ${name}`); });

3. Query Parameters

Query parameters can be appended to the URL after a question mark (?) and are accessed via req.query.

Example:

js
app.get('/search', (req, res) => { const { query, page } = req.query; res.send(`Search term: ${query}, Page number: ${page}`); });
  • If the URL is /search?query=express&page=2, the response will be Search term: express, Page number: 2.

4. Route Methods

Express allows you to handle different types of HTTP requests (GET, POST, PUT, DELETE) at the same route or different routes.

Example:

js
// Handle GET request (retrieving data) app.get('/item', (req, res) => { res.send('GET request for item'); }); // Handle POST request (creating data) app.post('/item', (req, res) => { res.send('POST request for item'); }); // Handle PUT request (updating data) app.put('/item/:id', (req, res) => { res.send(`PUT request for item with ID: ${req.params.id}`); }); // Handle DELETE request (deleting data) app.delete('/item/:id', (req, res) => { res.send(`DELETE request for item with ID: ${req.params.id}`); });

5. Route Handlers (Callback Functions)

Express route handlers are just JavaScript functions that define the behavior when the route is matched. These handlers take two arguments: req (request) and res (response).

Example:

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

You can also chain multiple handlers for a single route, which is useful for middleware or pre-processing.

Example with Middleware:

js
app.use('/user/:id', (req, res, next) => { console.log(`Request to /user with ID: ${req.params.id}`); next(); // Continue to the next middleware or route handler }); app.get('/user/:id', (req, res) => { res.send(`User details for ID: ${req.params.id}`); });

6. Route Groups with Express Router

The Router object in Express helps organize routes into modular, reusable units. This is especially useful in large applications where routing logic can get complex.

Example using express.Router:

js
const express = require('express'); const app = express(); const router = express.Router(); // Define routes for 'users' router.get('/', (req, res) => { res.send('List of all users'); }); router.get('/:id', (req, res) => { res.send(`User details for ID: ${req.params.id}`); }); // Mount the router to a specific path app.use('/users', router); // Start the server app.listen(3000, () => { console.log('Server is running on port 3000'); });

In this example:

  • /users/ will display “List of all users”.
  • /users/:id will display “User details for ID: {id}”.

This helps keep routes organized and avoid having one massive list of route definitions.

7. Route Chaining

You can chain multiple route handlers for the same route and HTTP method. This allows you to reuse code and organize logic more efficiently.

Example:

js
app.route('/book') .get((req, res) => { res.send('Get all books'); }) .post((req, res) => { res.send('Add a new book'); }) .put((req, res) => { res.send('Update a book'); });

This eliminates repetitive code for the same path and HTTP method.

8. Handling Errors in Routes

You can handle errors by using next in route handlers. If an error occurs, pass it to the next middleware (typically an error handler).

Example:

js
app.get('/data', (req, res, next) => { try { // Imagine some logic that can throw an error throw new Error('Something went wrong!'); } catch (error) { next(error); // Pass the error to the next middleware (error handler) } }); // Global error handler app.use((err, req, res, next) => { res.status(500).send(`Error occurred: ${err.message}`); });

9. Using HTTP Status Codes in Responses

Express allows you to set custom HTTP status codes in your responses using res.status(). This helps communicate the outcome of the request (success, error, etc.).

Example:

js
app.get('/success', (req, res) => { res.status(200).send('Request was successful'); }); app.get('/notfound', (req, res) => { res.status(404).send('Resource not found'); }); app.get('/servererror', (req, res) => { res.status(500).send('Internal server error'); });

10. Route Handling with Wildcards

You can use wildcard routes to handle dynamic paths or catch-all routes.

Example:

js
app.get('*', (req, res) => { res.send('Catch-all route'); });

This route will match any request that hasn’t been matched by other routes.


Conclusion

Express routing is one of the fundamental aspects of building web applications with Express.js. It provides a simple yet powerful way to map URLs to specific functionality and handle client requests based on the HTTP method. By organizing your routes and using features like route parameters, query parameters, routers, and middleware, you can easily manage complex web applications.

For large applications, it’s common to modularize routes with express.Router(), allowing for a scalable and maintainable route structure.

Share:

More Posts

Browser DevTools Tips

Browser DevTools are a powerful set of tools that allow developers to inspect, debug, and optimize web pages. Whether you’re a front-end developer or someone

ES6 Features

ES6 (ECMAScript 2015) introduced a number of significant updates to JavaScript, which made the language more powerful, easier to work with, and more consistent. Here’s

Responsive Design

Responsive design is a web design approach aimed at creating websites that provide optimal viewing and interaction experiences across a wide range of devices. Whether

SCSS Nesting

SCSS Nesting is a feature in Sass (Syntactically Awesome Style Sheets), which is a CSS preprocessor that extends CSS with features like variables, mixins, inheritance,

API Rate Limiting

API rate limiting is a technique used to control the amount of incoming requests to a server or service over a specific period of time.

CSS Animations

CSS animations allow you to animate the transitions of various properties, like colors, sizes, positions, or even more complex transformations. They can be keyframed or

CSS Grid Layout

CSS Grid Layout is a powerful layout system that allows you to create complex, flexible grid-based designs with minimal effort. It provides a way to

SQL Joins Explained

SQL JOINS are used to combine rows from two or more tables based on a related column between them. They allow you to retrieve data

Semantic HTML

This post provides a brief overview of Semantic HTML in modern web development. More detailed content can be added here.

CSS Pseudo Elements

This post provides a brief overview of CSS Pseudo Elements in modern web development. More detailed content can be added here.

Progressive Web Apps

This post provides a brief overview of Progressive Web Apps in modern web development. More detailed content can be added here.

Axios vs Fetch

This post provides a brief overview of Axios vs Fetch in modern web development. More detailed content can be added here.

Babel Explained

This post provides a brief overview of Babel Explained in modern web development. More detailed content can be added here.

Async/Await in JS

This post provides a brief overview of Async/Await in JS in modern web development. More detailed content can be added here.

Fetch API Usage

This post provides a brief overview of Fetch API Usage in modern web development. More detailed content can be added here.

Firebase Authentication

This post provides a brief overview of Firebase Authentication in modern web development. More detailed content can be added here.

GraphQL Intro

This post provides a brief overview of GraphQL Intro in modern web development. More detailed content can be added here.

LocalStorage vs SessionStorage

This post provides a brief overview of LocalStorage vs SessionStorage in modern web development. More detailed content can be added here.

Nuxt.js Intro

This post provides a brief overview of Nuxt.js Intro in modern web development. More detailed content can be added here.

Tailwind CSS Basics

This post provides a brief overview of Tailwind CSS Basics in modern web development. More detailed content can be added here.

JS Unit Testing

This post provides a brief overview of JS Unit Testing in modern web development. More detailed content can be added here.

REST API Design

This post provides a brief overview of REST API Design in modern web development. More detailed content can be added here.

Web Accessibility (a11y)

This post provides a brief overview of Web Accessibility (a11y) in modern web development. More detailed content can be added here.

Microservices Overview

This post provides a brief overview of Microservices Overview in modern web development. More detailed content can be added here.

Service Workers

This post provides a brief overview of Service Workers in modern web development. More detailed content can be added here.

DOM Manipulation

This post provides a brief overview of DOM Manipulation in modern web development. More detailed content can be added here.

Intro to TypeScript

This post provides a brief overview of Intro to TypeScript in modern web development. More detailed content can be added here.

Authentication in Web Apps

This post provides a brief overview of Authentication in Web Apps in modern web development. More detailed content can be added here.

Svelte for Beginners

This post provides a brief overview of Svelte for Beginners in modern web development. More detailed content can be added here.

JavaScript Closures

This post provides a brief overview of JavaScript Closures in modern web development. More detailed content can be added here.

Vue Directives

This post provides a brief overview of Vue Directives in modern web development. More detailed content can be added here.

Node.js Modules

This post provides a brief overview of Node.js Modules in modern web development. More detailed content can be added here.

HTML Basics

This post provides a brief overview of HTML Basics in modern web development. More detailed content can be added here.

OAuth 2.0 Basics

This post provides a brief overview of OAuth 2.0 Basics in modern web development. More detailed content can be added here.

JWT Authentication

This post provides a brief overview of JWT Authentication in modern web development. More detailed content can be added here.

Flexbox Tricks

This post provides a brief overview of Flexbox Tricks in modern web development. More detailed content can be added here.

CORS Explained

This post provides a brief overview of CORS Explained in modern web development. More detailed content can be added here.

SEO for Developers

This post provides a brief overview of SEO for Developers in modern web development. More detailed content can be added here.

WebSockets Overview

This post provides a brief overview of WebSockets Overview in modern web development. More detailed content can be added here.

React Hooks

This post provides a brief overview of React Hooks in modern web development. More detailed content can be added here.

Debounce vs Throttle

This post provides a brief overview of Debounce vs Throttle in modern web development. More detailed content can be added here.

Bootstrap Grid System

This post provides a brief overview of Bootstrap Grid System in modern web development. More detailed content can be added here.

Next.js Routing

This post provides a brief overview of Next.js Routing in modern web development. More detailed content can be added here.

Webpack Basics

This post provides a brief overview of Webpack Basics in modern web development. More detailed content can be added here.

SASS Variables

This post provides a brief overview of SASS Variables in modern web development. More detailed content can be added here.

Cookies vs Tokens

This post provides a brief overview of Cookies vs Tokens in modern web development. More detailed content can be added here.

MongoDB Queries

This post provides a brief overview of MongoDB Queries in modern web development. More detailed content can be added here.

HTML5 Forms

This post provides a brief overview of HTML5 Forms in modern web development. More detailed content can be added here.

Web Security Tips

This post provides a brief overview of Web Security Tips in modern web development. More detailed content can be added here.

Ultimate Web Development Roadmap

Ultimate Web Development Roadmap

Ultimate Web Development Roadmap: Step-by-Step Guide to Building Modern, Scalable Websites Introduction Web technology changes fast. New tools and best practices appear all the time.

Web Development future in 2026

Web Development future in 2026

So yeah, I’ve been thinking a lot about where web development is heading. Not in the “buzzwordy LinkedIn post” kind of way, but more like…

Send Us A Message