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

205
Views
ExpressJs version route through header or query params

I have different version api developed using ExpressJs, I get version detail either through header or through query string like this example.com/users?version=1 and example.com/users?version=2 or I get in header.

I want to route my application api by query param I get through url app.js

app.use('/', (req, res, next) => {
    app.use(require('./v'+req.query.version));
    next();
});

I have two version in folder v1/index.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World! v01')
});

module.exports = app;

and v2/index.js as

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World! v02')
});

module.exports = app;

when I call api through url I only get response of version I call first

Like if I first call example.com/users?version=1 than I will get response as 'Hello World! v01',

after this if I call example.com/users?version=2 I get response as 'Hello World! v01'

If I call version=2 first time after starting script I will get 'Hello World! v02' response every time.

I don't want to have application like example.com/v1 is their any way to get solve this version issue using query param or through header.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Why you want to import dynamically may cause issues.

let say if I pass example.com/users?version=23424

// v1/index
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
  res.send("Hello World! v01");
});
module.exports = router;

// v2/index
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
  res.send("Hello World! v02");
});
module.exports = router;

// server
const express = require("express");
const app = express();
const v1 = require("./v1/index");
const v2 = require("./v2/index");
app.use("/", (req, res, next) => {
const { version } = req.query;
  if (version !== "1" && version !== "2") {
    return res.json({
      message: "Not found",
    });
  }
  const router = version === "1" ? v1 : v2;
  router(req, res, next);
  next();
});
about 4 years ago · Juan Pablo Isaza 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!