Express global router for a DRY code

This post is about using a global router in Express for a DRY code.

When developing a Node.js app with Express, we'll usually have two or more routes.
If we use the express.Router class to put each route in a separate file, we'll always have to begin with the same block of code:

const express = require("express")
const router = express.Router()

There is a better approach by using a global router.

In the main server file, we'll parse an express.Router to a global.router assigned to a router variable, and in each route we'll only use this global router.

Let's say we have only two routes: main "/" and about "/about".
Following the common way, any route in it's own file will look like:

// /routes/aRoute.js
const express = require("express")
const router = express.Router()

router.get("/", (req, res) => {
    res.send("A route content")
})

Then, in the main server file we'll have:

// /index.js
...
app.use("/a-route", require("./routes/aRoute"))
...

But by using a global router we can do the following:

// /index.js

const express = require("express")
const app = express()

// Parse an express router to a global router variable
const router = (global.router = express.Router())
// Use the global router variable
app.use(router)

// Routes
app.use("/", require("./routes/main"))
app.use("/", require("./routes/about"))

// Launching the app on port 3000
app.listen(3000, () => {
    console.log(`App 🚀 @ http://localhost:3000`)
})

Then our two routes will look like so:

// /routes/main.js

const router = global.router

router.get("/", (req, res) => {
    res.send("Welcome to the main route")
})

module.exports = router
// /routes/about.js

const router = global.router

router.get("/about", (req, res) => {
    res.send("Welcome to the about route")
})

module.exports = router

Hope this will help you write a DRY code.

Note: The background image is a photo by Alina Grubnyak.

SYA,
LebCit.