Connecting Express Routers

Introduction

Express routers help modularize your application by grouping related routes together. Once you've set up your router instances, the next step is to connect them to your main application. Think of this process as attaching wings to an airplane—it's what makes your application truly fly by directing incoming requests to the appropriate router.

In this guide, you'll learn how to:

Importing Express Routers

Start by importing the router modules into your main app.js file. Here's how to do it:


const express = require('express');
const home = require('./routes/home');
const schedule = require('./routes/schedule');
const roster = require('./routes/roster');

      

Note that the require directive uses a relative path (starting with ./) to indicate that these modules are local files in your project.

Think of this step as connecting different "rooms" (routers) to the main "hallway" (your application), allowing requests to be routed to the appropriate section.

Mounting Routers

To connect your router instances to the main application, use the app.use() method. Here's an example:


// Create the Express app
const app = express();

// Mount router instances
app.use(home);
app.use(schedule);
app.use(roster);

      

The app.use() method exposes the router instance to handle incoming HTTP requests. The combination of router mount paths and the routes defined within each router creates a clean hierarchy, such as:


/home
/schedule/week
/schedule/week/:day
/roster
/roster/:position

      

Defining Route Prefixes

You can prepend a base path for each router by passing an additional argument to app.use(). For example:


// Mount routers with prefixes
app.use('/schedule', schedule);

      

This approach ensures that all routes in the schedule router are prefixed with /schedule. The router definition becomes simpler:


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

      

Think of the base path as a street address. By defining it in one place, all routes in the router inherit the "street," and you only need to define the "house number" (specific paths) within the router.

Best Practices

To make your codebase more maintainable, follow these best practices:

Here’s an example of cleanly mounted routers:


// app.js
app.use('/home', home);
app.use('/schedule', schedule);
app.use('/roster', roster);

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

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

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

      

What You’ve Learned

By modularizing routes with Express routers, you can keep your codebase structured, scalable, and easy to navigate. Think of this as building a well-organized library where each section (router) has its own dedicated shelves (routes).