Express Router

Previously, we've learnt to declare our routes directly within our server.ts file:

/*
* server.ts
*/
import express from 'express'
const port = 3000
const server = express()
server.get('/', (req, res) => {
res.send('<h1>Hello world</h1>')
})

However, as we add more routes to our Express server, this can become cumbersome. Express has built in functionality to separate our routes and make our code more modular:

Express Router

We can use express.Router to create modular route handlers. The following example creates a router as a module, defines some routes, and mounts the router module on a path in the main app (server.ts).

Let's say we want to create a /birds route where we can:

  • view a list of birds via get /birds
  • view a single bird by id via get /birds/:id
  • add a new bird via post /birds

Our code may look like this:

/*
* server.ts
*/
const express = require('express')
const birdRoutes = require('./bird-routes.ts')
const server = express()
server.use('/birds', birdRoutes)
server.get('/', (req, res) => {
// ...
})
/*
* bird-routes.ts
*/
import express from 'express'
const router = express.Router()
router.get('/', function (req, res) {
// ...
})
router.get('/:id', function (req, res) {
// ...
})
router.post('/', function (req, res) {
// ...
})
export default router

Notice the differences:

  • server.ts

    • We use server.use instead of server.get to add our routes to our server.
    • We put the name of the route /birds to specify that our bird-routes.ts will handle ALL routes that start with /birds.
  • bird-routes.ts

    • Notice how we don't specify birds anywhere in this file? This is because we have already specified this in our server.ts! This means that even though our first route is to /, it is actually /birds because we have prefixed the route in our server file.
    • We import express and define const router = express.Router() as a separate variable.
    • We specify router.get and router.post for the individual routes and these take in two parameters - a path / and a req, res callback function.
    • We export the router, and not the individual functions.

Resources