Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Express.js Advanced Routing
tutorial

Express.js Advanced Routing

As your application grows, you'll need more sophisticated routing techniques. Express provides advanced routing features like `app.all()` to handle all HTTP methods, and `express.Router()` to create modular, mountable route handlers.

The app.all() Method

`app.all()` is a special routing method that responds to all HTTP methods (GET, POST, PUT, DELETE, etc.) on a specific path. It's useful for middleware-like functionality or handling all requests to a particular endpoint.
<!-- Handle all methods on /api/* -->
app.all('/api/*', (req, res, next) => {
  console.log(`API request received: ${req.method} ${req.url}`);
  next(); <!-- Pass control to next handler -->
});

<!-- Authentication check for all routes under /admin -->
app.all('/admin/*', (req, res, next) => {
  if (!req.headers.authorization) {
    return res.status(401).send('Unauthorized');
  }
  next();
});

Express Router

`express.Router()` is a powerful feature that lets you create modular route handlers. Think of it as a mini-Express application that can only perform routing and middleware functions.

Routers help you organize your code by feature or resource. Instead of having all routes in one file, you can split them into logical groups.

Creating a Router
<!-- routes/users.js -->
const express = require('express');
const router = express.Router();

<!-- Middleware specific to this router -->
router.use((req, res, next) => {
  console.log('User router accessed at:', new Date().toISOString());
  next();
});

<!-- Define routes on the router object -->
router.get('/', (req, res) => {
  res.json([{ id: 1, name: 'John' }]);
});

router.get('/:id', (req, res) => {
  res.json({ id: req.params.id, name: 'John' });
});

router.post('/', (req, res) => {
  res.status(201).json({ message: 'User created', user: req.body });
});

module.exports = router;

Using Routers in Main App
<!-- app.js -->
const express = require('express');
const userRouter = require('./routes/users');
const productRouter = require('./routes/products');

const app = express();
app.use(express.json());

<!-- Mount routers at specific paths -->
app.use('/users', userRouter);
app.use('/products', productRouter);

app.listen(3000);

<!-- Now routes are available at: -->
<!-- GET /users -->
<!-- GET /users/123 -->
<!-- POST /users -->
<!-- GET /products -->
<!-- etc. -->

Router Middleware

Routers can have their own middleware that only applies to routes in that router:
const router = express.Router();

<!-- This runs only for /admin routes -->
router.use((req, res, next) => {
  if (!req.user?.isAdmin) {
    return res.status(403).send('Forbidden');
  }
  next();
});

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

Combining app.all() with Router
const router = express.Router();

<!-- Log all requests to this router -->
router.all('*', (req, res, next) => {
  console.log(`[API] ${req.method} ${req.originalUrl}`);
  next();
});

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

Two Minute Drill

  • `app.all()` matches all HTTP methods on a path – useful for middleware or handling any request.
  • `express.Router()` creates modular route handlers that can be mounted in the main app.
  • Routers can have their own middleware, making code organization cleaner.
  • Mount routers with `app.use()` at specific path prefixes.
  • Advanced routing helps maintain large applications by separating concerns.

Need more clarification?

Drop us an email at career@quipoinfotech.com