Defining Express Routers

Introduction

As your Express applications grow in complexity, managing all routes within a single app.js file becomes cumbersome. Imagine trying to navigate a cluttered room filled with stacks of paper—this is what a large app.js file feels like! To maintain clarity and organization, Express provides a powerful feature called routers.

Routers allow developers to create modular, mountable route handlers for specific sections of an application. This keeps codebases organized, readable, and easier to maintain. Let's dive into how to use express.Router to create a basketball team application with dedicated routes for "Home", "Schedule", and "Roster".

What Are Express Routers?

Think of an Express router as a "mini-app" that handles specific parts of your web application. Just as a house is divided into rooms for different purposes, routers divide your application into sections, each managing its own routes.

For example, a customer order management application might have routers for customers, products, and orders. Each router encapsulates related routes and logic, making the code easier to navigate.


App/
├── Customers (/customer)
│   ├── Add Customer (POST /customer)
│   ├── View Customer Details (GET /customer/:id)
│   ├── Edit Customer (PUT /customer/:id)
│   └── Delete Customer (DELETE /customer/:id)
├── Products (/product)
│   ├── View All Products (GET /product)
│   └── View Product Details (GET /product/:id)

      

Creating Express Routers

To create modular routes, you'll use the express.Router class. Let's build routers for a basketball team application with "Home", "Schedule", and "Roster" pages.

Follow these steps:

Step 1: Set Up a Routes Folder

Create a routes folder in your project root. Inside this folder, create three files: home.js, schedule.js, and roster.js.

Step 2: Define a Router in Each File

Each router is an instance of the express.Router class. Here's the boilerplate code:


// Example boilerplate for a router
const express = require('express');
const router = express.Router();

// Define your routes below
module.exports = router;

      

Step 3: Add Routes

Here’s how to define routes for each file:

Home Router


// home.js
router.get('/home', (req, res) => {
  res.send('Our team homepage');
});

      

Schedule Router


// schedule.js
const weeklySchedule = [false, true, true, false, true, false, true];

router.get('/schedule/week', (req, res) => {
  res.json(weeklySchedule);
});

router.put('/schedule/week/:day', (req, res) => {
  const day = parseInt(req.params.day);
  weeklySchedule.splice(day, 1, true);
  res.json(weeklySchedule);
});

      

Roster Router


// roster.js
const roster = {
  pg: 'Randy',
  sg: 'Anthony',
  sf: 'Noah',
  pf: 'Benjamin',
  c: 'Miles'
};

router.get('/roster', (req, res) => {
  res.json(roster);
});

router.put('/roster/:position', (req, res) => {
  const position = req.params.position;
  const newPlayer = req.body.name;
  roster[position] = newPlayer;
  res.json(roster);
});

router.delete('/roster/:position', (req, res) => {
  const position = req.params.position;
  delete roster[position];
  res.json(roster);
});

      

Exporting and Mounting Routers

After defining the routes, export each router using module.exports. Then, in your main app.js file, import and mount the routers using app.use():


// app.js
const express = require('express');
const homeRouter = require('./routes/home');
const scheduleRouter = require('./routes/schedule');
const rosterRouter = require('./routes/roster');

const app = express();
app.use(express.json()); // Middleware for parsing JSON

app.use(homeRouter);
app.use(scheduleRouter);
app.use(rosterRouter);

const port = 3000;
app.listen(port, () => console.log(\`Server running on port \${port}\`));

      

What You’ve Learned

Routers make your application scalable, maintainable, and easier to read. Think of them as filing cabinets organizing your application’s logic into separate, neat folders.