express.js global router configurations.

Duckdev84
2 min readNov 14, 2021

--

express.js global router configurations.

After creating a simple express.js I would like to make many services, route names. I found that so complicated to manage many files that work together. Problems as the require function make many conflicts with each other. In this’s story, I will tell how to separate and combine the router file.

Declare a global router, parse an express router to a variable’s router, and then use it.

const router = (global.router = (express.Router()))
app.use(router)

Create router folder, name’s routes, then create two files inside, products.js and users.js. Each file writes the same code. This story only explains how separate and combined the router file is. The file calls the express.router() in the router and declares a route on GET method. The first parameter requires a string value of the route name, URI. Other parameters after that can parse callback function to them. In the default callback function that required the req and res parameters, now only used the res to send some string value for sure it’s work fine.

routes
|___ products.js
|___ users.js

products.js

const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.send('This products route.')
})
module.exports = router

users.js

const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.send('This users route.')
})
module.exports = router

Back to the index file, import them with require function, and then apply them to the express.

const express = require('express')
const app = express()
const router = (global.router = (express.Router()))
const productRouter = require('./routes/products')
const userRouter = require('./routes/users')
app.use(router)
app.use('/products', productRouter)
app.use('/users', userRouter)
app.listen('3001', () => {
console.log('started: localhost:3001')
})

Good luck ^_^

--

--

No responses yet