27

Does anyone know of a way to configure express to add a prefix before all routes automatically? for example, currently I have:

/

/route1

/route2

However, I want to add a prefix like:

/prefix/

/prefix/route1

/prefix/route2

Right now I need to define prefix manually to all of my routes but would like a more automated/configurable way. Can someone help?

Thanks in advance!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200
  • See https://stackoverflow.com/questions/4375554/is-it-possible-to-set-a-base-url-for-nodejs-app but be careful to note which answers are for older versions of Express. – skirtle Nov 01 '17 at 16:16

2 Answers2

34

You can use the express Router() for this.

You can use the router like you would use your express app. So for example:

const router = express.Router()
router.use(() => {}); // General middleware
router.get('/route1', () => {})
router.get('/route2', () => {})
router.post('/route2', () => {})

And then attach the router to your express app using:

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

https://expressjs.com/en/4x/api.html#router

rchavarria
  • 930
  • 10
  • 16
Dominic
  • 3,353
  • 36
  • 47
  • Thanks! This worked for me. However, it messed up my `res.render('...html')` (going to my route just has a blank screen now). Do you know if I need to re-configure how my static files are sent? – Trung Tran Nov 01 '17 at 16:27
  • @TrungTran hard to tell without an error message. Could be that you're using relative paths and moved the file into a different directory – Dominic Nov 01 '17 at 16:44
  • By doing this, its working for both API's. ie, works for `/prefix/route1` and `/route1`. How to restrict it for `/prefix/route1` only? – KTM Dec 21 '20 at 13:21
  • what if i want to add the same prefix to all of them? – mercury Mar 07 '21 at 17:15
10

routes.js

module.exports = (app) => {
   app.post('/route', (req, res) => {
      res.status(status);
      res.send(data);
   }); 

   app.get('/route', (req, res) => {
      res.status(status);
      res.send(data);
   }); 

   return app; 
};

Server.js

const router = express.Router()
const routes = require('./routes')(router, {});
app.use('/PREFIX_HERE', routes)

REFER : https://expressjs.com/en/guide/using-middleware.html

Anandan K
  • 1,380
  • 2
  • 17
  • 22