0
0
Expressframework~5 mins

Why modular routing matters in Express

Choose your learning style9 modes available
Introduction

Modular routing helps keep your code organized and easy to manage by splitting routes into separate files.

When your app has many routes and you want to avoid one big file.
When different team members work on different parts of the app.
When you want to reuse route logic in multiple places.
When you want to make your app easier to test and maintain.
Syntax
Express
const express = require('express');
const router = express.Router();

// Define routes
router.get('/path', (req, res) => {
  res.send('Response');
});

module.exports = router;

Use express.Router() to create a mini-router.

Export the router to use it in your main app file.

Examples
This example creates a router for user-related routes.
Express
const express = require('express');
const router = express.Router();

router.get('/users', (req, res) => {
  res.send('User list');
});

module.exports = router;
This example handles a login route in a separate router.
Express
const express = require('express');
const router = express.Router();

router.post('/login', (req, res) => {
  res.send('Login page');
});

module.exports = router;
Sample Program

This example shows a main app file using a modular router for user routes. The user routes are in a separate file and handle listing users and showing a user by ID.

Express
const express = require('express');
const app = express();

// Import modular routes
const userRoutes = require('./routes/users');

// Use modular routes with a prefix
app.use('/users', userRoutes);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

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

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

router.get('/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

module.exports = router;
OutputSuccess
Important Notes

Modular routing keeps your main app file clean and focused.

It makes adding or changing routes easier without breaking other parts.

Use clear route prefixes to avoid conflicts between modules.

Summary

Modular routing splits routes into separate files for better organization.

It helps teams work together and keeps code easier to maintain.

Use express.Router() and app.use() to connect modules.