Search code examples
node.jsexpressroutes

How to add prefix to all node / express routes


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!


Solution

  • 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