ExpressJS Advanced Routing (app.all router)
So far, you've learned about basic routing with specific HTTP methods. But Express offers more powerful routing features that help you write cleaner and more maintainable code. Let's explore
app.all() and the Express Router.The app.all() Method
app.all() is a special routing method that matches all HTTP methods (GET, POST, PUT, DELETE, etc.) for a specific path. It's useful for handling things like authentication, logging, or serving the same response regardless of the method.// This will run for any HTTP method on /secret
app.all('/secret', (req, res) => {
res.send('This is a secret area. No matter how you request it, you get this response.');
});A common use case is middleware-like behavior:
// Check authentication for all requests to /admin/*
app.all('/admin/*', (req, res, next) => {
if (!req.user) {
res.status(401).send('Unauthorized');
} else {
next(); // Continue to the actual route
}
});The Express Router
As your application grows, keeping all routes in one file becomes messy. Express Router helps you organize routes into separate modules. Think of it as mini-Express applications that handle specific groups of routes.
Creating a Router
Create a new file called
routes/users.js:const express = require('express');
const router = express.Router();
// All routes here start with /users (as we'll mount them that way)
router.get('/', (req, res) => {
res.send('Get all users');
});
router.get('/:userId', (req, res) => {
res.send(`Get user with ID ${req.params.userId}`);
});
router.post('/', (req, res) => {
res.send('Create a new user');
});
router.put('/:userId', (req, res) => {
res.send(`Update user with ID ${req.params.userId}`);
});
router.delete('/:userId', (req, res) => {
res.send(`Delete user with ID ${req.params.userId}`);
});
module.exports = router;Using the Router in Your Main App
In your main
app.js:const express = require('express');
const app = express();
// Import routers
const userRouter = require('./routes/users');
const productRouter = require('./routes/products');
// Mount routers
app.use('/users', userRouter);
app.use('/products', productRouter);
app.listen(3000);How It Works
When you mount a router with
app.use('/users', userRouter), all routes defined in userRouter are prefixed with /users. So:router.get('/')becomes/usersrouter.get('/:userId')becomes/users/:userIdrouter.post('/')becomes/users(POST method)
Router-Level Middleware
Routers can also have their own middleware that only applies to routes in that router:
// In routes/users.js
router.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
// This middleware runs for all routes in this routerBenefits of Using Router
- Organization: Related routes are grouped together
- Reusability: You can mount the same router at different paths
- Maintainability: Easier to manage large codebases
- Middleware isolation: Apply middleware only to specific route groups
Two Minute Drill
app.all()matches any HTTP method for a given path, useful for middleware or simple responses.- Express Router helps organize routes into separate modules.
- Create a router with
express.Router(), define routes on it, and export it. - Mount routers in your main app with
app.use(). - Routers can have their own middleware that applies only to their routes.
Need more clarification?
Drop us an email at career@quipoinfotech.com
