node.jsarchitectureweb-architecture

Nodejs Database configuration based on accessed domain


I have two domains abc.com and xyz.com pointing to the same NodeJS server. Based on the domain I want to load the configuration that will persist for that domain i.e. for xyz.com I wanna connect to Database1 and for abc.com I wanna connect to Database2.

How do I go about doing this? Is it even possible or recommended to do so?

I started with loading the configuration on the first request by getting the hostname from req.hostname. Is there any better way to do this?

Architecture


Solution

  • Multiple strategies -

    1. Deploy the same code multiple times but on different ports.

    Your reverse proxy sends the request to the correct server. I do this currently by hosting multiple ghost blogs on the same vps. One runs on port 3000, another on 3010.

    Pros - Less fragile setup, easier scaling, application need not be aware of operational environment. If one domain comes under attack, the other is not automatically a casualty.

    Cons - Might not be possible in resource constrained environments. Deployments can involve repetitive work.

    2. Read the hostname

    Great option if the feature set is pretty much the same but only the domain name changes. You read the configuration file as you stated depending on the hostname.

    Pros - Easier deployment, great option for resource constrained environments.

    Cons - Unnecessarily tight coupling, all domains will become unavailable in case of server errors, scaling could be an issue.

    Personally, I prefer deploying on different ports unless and until the code requires depending on hostnames. If you are just building a product where some unique identifier needs to be present in the URL like mycompany.slack.com then using subdomains in dns might be a better idea.