How to separate routes on Node.js and Express 4?

Sometimes, we want to separate routes on Node.js and Express 4.

In this article, we’ll look at how to separate routes on Node.js and Express 4.

How to separate routes on Node.js and Express 4?

To separate routes on Node.js and Express 4, we can put our routes into a separate and call require to add them.

For instance, we write

app.js

const express = require('express');
const app = express();

app.use(require('./routes'));

const server = app.listen(8000, () => {
  const host = server.address().address
  const port = server.address().port
  console.log("listening at http://%s:%s", host, port)
})

to call app.use with require('./routes') to add the routes in routes.js.

Then in routes.js, we write

const express = require('express');
const router = express.Router();

router.use((req, res, next) => {
  next();
});

router.get('/', (req, res) => {
  res.send('home page');
});

router.get('/about', (req, res) => {
  res.send('About us');
});


module.exports = router;

to create a router object with express.Router.

Then we call router.use and router.get to add the middleware and add GET endpoints.

Next, we set module.exports to router to export router so we can use require('./routes') to include the router and call app.use to add the routes.

Conclusion

To separate routes on Node.js and Express 4, we can put our routes into a separate and call require to add them.