subdomain base database connectivity (nodejs + express)

295 Views Asked by At

I have single repository of project and have multiple databases for different clients.

Following types of database naming and URL to connectivity that I am using to connect database based on access URL:

Client's Database

  • shreyas_db (http://shreyas.locahost:3001)
  • ajay_db (http://ajay.locahost:3001)
  • vijay_db (http://vijay.locahost:3001)

Please guide how to implement this structure in NodeJs with Express.

Thanks

1

There are 1 best solutions below

0
On

Here is the solution I figure out:

  1. Add a router

    app.use('/api', await APIRouter())

  2. connect to different DBS in router middleware. Get the subdomain(If you are using Nginx, you may found req.subdomains or req.host does not return what you expected, try to use req.headers.referer instead), use res.locals to save DB, so you can get it from every API call.

 export const APIRouter = async () => {
      
      const router = express.Router()
      const client = await connectDatabase()
    
      router.use(async (req, res, next) => {
        //const host = req.headers.referer?.replace("https://","");
        //const subdomain = host ? host.substring(0, host.indexOf('.')) : 'main'
        
        const subdomain = req.subdomains.length ? req.subdomains.length[0] : 'main'
        const db = client.db(subdomain)
    
        res.locals.db = {
            clients: db.collection<Client>('clients'),
          }
          next()
        }
      )
     return router
    };