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

182
Views
How can I dynamically assign a database path in Express.js based on login?

I have a backend service that I would like to use as a single point of entry for my web application, and dynamically assign a database path based on the user login. I realize that this is not a scalable solution. I intend to use it during a testing period with several clients (accessing the ALPHA database), and also setting up a demo (accessing the SAND database). I have the following module that I have written as a simple test to see if the login is for the demo user, all other logins will go to the other resource:

config.js

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

module.exports.dbPath = function  (login){
    console.log('login - ', login);
    if (login === 'demo@mysite.com'){
        return process.env.DB_SAND;
    } else {
        return process.env.DB_ALPHA;
    }
};

My question is, how can I manage each unique login and assign a globally accessible reference for that session to direct each user session consistently to the correct database? Am I overcomplicating this? If there is a different approach that would be a better practice I would welcome a suggestion in another direction.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I would use it as a middleware, and attach it to the req object for each user, something similar this:

module.exports = {
    dbPath: function(req, res, next){
       var login = req.body.login;
       console.log('login - ', login);
       if (login === 'demo@mysite.com'){
          req.dbPath = 'DB_SAND';
       } else {
          req.dbPath = 'DB_ALPHA';
       }
       next();
    }
};
over 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!