How to set a base URL for Node.js Express app?

Sometimes, we want to set a base URL for Node.js Express app.

In this article, we’ll look at how to set a base URL for Node.js Express app.

How to set a base URL for Node.js Express app?

To set a base URL for Node.js app, we can call app.use with the base URL` and a route object.

For instance, we write

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

router.use((req, res, next) => {
  console.log('%s %s %s', req.method, req.url, req.path);
  next();
});

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

router.use((req, res, next) => {
  res.send('Hello World');
});

app.use('/foo', router);

app.listen(3000);

to create a new router with express.Router.

Then we add some middlewares and routes with router.use.

And then we call app.use with '/foo' and router to nest router with /foo as the base URL for the routes.

Conclusion

To set a base URL for Node.js app, we can call app.use with the base URL` and a route object.