Express.js Routing

Learn how to define routes in Express.js, handle HTTP methods, use route parameters, and organize your application endpoints effectively.

Overview

Routing in Express.js refers to how your application responds to client requests at specific endpoints (URIs) and HTTP methods (GET, POST, PUT, DELETE, etc.).

Express provides a clean and intuitive API for defining routes. Each route can have one or more handler functions that execute when the route is matched.

Basic Routing

The most basic route in Express consists of a path and a callback function. The callback receives the request and response objects, allowing you to process the request and send a response.

Route Methods

Express supports all HTTP methods including GET, POST, PUT, PATCH, DELETE, and more. You can also use `app.all()` to handle all methods for a specific route.

Route Parameters

Route parameters are named URL segments used to capture values at specific positions in the URL. They're defined using a colon followed by the parameter name.

Route Handlers

You can provide multiple callback functions for a single route. This is useful for middleware-like behavior where you might want to validate data before processing.

Express Router

For larger applications, Express Router allows you to create modular, mountable route handlers. A Router instance is a complete middleware and routing system.

Code Examples

Basic Route Definition

app.js
const express = require('express');
const app = express();

// GET request to homepage
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// POST request to /users
app.post('/users', (req, res) => {
  res.send('Create a user');
});

app.listen(3000);

Route Parameters

routes/users.js
// Route with parameters
app.get('/users/:userId', (req, res) => {
  res.send(`User ID: ${req.params.userId}`);
});

// Multiple parameters
app.get('/users/:userId/books/:bookId', (req, res) => {
  const { userId, bookId } = req.params;
  res.json({ userId, bookId });
});

Express Router

routes/api.js
const express = require('express');
const router = express.Router();

// Middleware specific to this router
router.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

router.get('/', (req, res) => {
  res.send('API Home');
});

router.get('/users', (req, res) => {
  res.json({ users: [] });
});

module.exports = router;

// In app.js
const apiRouter = require('./routes/api');
app.use('/api', apiRouter);

Frequently Asked Questions

What is the difference between app.get() and app.use()?
app.get() handles only GET requests to a specific path, while app.use() handles all HTTP methods and is typically used for middleware. app.use() also matches paths that start with the specified path.
How do I handle 404 errors in Express?
Add a catch-all middleware at the end of your route definitions using app.use((req, res) => { res.status(404).send('Not Found'); }). This will handle any requests that don't match previous routes.
Can I use async/await in Express route handlers?
Yes! Express 5 has built-in support for async route handlers. For Express 4, you should wrap async handlers or use a wrapper function to catch errors and pass them to next().

Need expert help with Express.js?

Our team at Slashdev.io builds production-ready Express.js applications.