How to pass an app instance to routes from a different file with Express?

Sometimes, we want to pass an app instance to routes from a different file with Express.

In this article, we’ll look at how to pass an app instance to routes from a different file with Express.

How to pass an app instance to routes from a different file with Express?

To pass an app instance to routes from a different file with Express, we can call require on the module with the routes in the module that we defined the app instance in.

For instance, we write

app.js

const app = module.exports = express();
app.use(app.router);

require('./routes');

to export the app instance created by express.

Then in routes/index.js, we write

const app = require('../app');

app.get('/', (req, res, next) => {
  res.render('index');
});

require('./user');
require('./blog');

to require app.js and then call app.get to add a GET route.

We also call require with other route modules which require app individually themselves to add the routes from those files.

Conclusion

To pass an app instance to routes from a different file with Express, we can call require on the module with the routes in the module that we defined the app instance in.