Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Switch between routers Express

I want to display a website completely different in function of an arbitrary value.

Let's say I have two routers

const express = require('express');
const app = express();
const router1 = express.Router();
router1.get('/', (req, res, next) => res.json({message: 'I am the router1'}))
const router2 = express.Router();
router2.get('/', (req, res, next) => res.json({message: 'I am the router2'}))
app.use((req, res, next) => {
    if(Math.random() > 0.5) {
        // Use router1
    } else {
        // Use router2
    }
})

I have no idea how I can do that. I will have a lots of routes (router.get, router.post) I don't want to check that on each route

Thanks

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

This can also be done by usage of .next('router') method.

Here is an example:

const router1 = express.Router();

router1.use((req, res, next) => { 

  console.log("This gets called everytime!");

  if(Math.random() > 0.5) 
    next('router');//skip to next router object
  else
    next();//continue with current router
});

router1.get('/',(req, res, next) => {
  console.log("Continuing with current router");
  res.send("Continuing with current router");
});


const router2 = express.Router();

router2.get('/', (req, res, next) => {
  console.log("Skipped Router 1, continuing with router 2");
  res.send("Skipped Router 1, continuing with router 2");
});

//binding both routers here
app.use("*", router1, router2);

.next('router') basically skips to next router object, which has been mentioned in the app.use line, if only next() is used then it continues with current router methods.

about 4 years ago · Santiago Trujillo Report

0

Just return a call to the router:

app.use((req, res, next) => {
    if(Math.random() > 0.5) {
        return router1(req, res, next)
    } else {
        return router2(req, res, next)
    }
})
about 4 years ago · Santiago Trujillo Report

0

Why not just?

if(Math.random() > 0.5) {
    app.use(router1);
} else {
    app.use(router2);
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!