Change Env per subdomain

Hey guys,

I’ve been using Adonis (Adonuxt template) for a while but I just came across a fairly unusual use case and I could really use some insight.

I am trying to set up a multi tenant app where each subdomain gets it’s own specific ENV (loaded first from the .env file then overridden by the values loaded from a DB), so that:

  • subA.domain.com => database: A, Env to be loaded from database A, table “Env”
  • subB.domain.com => database: B, Env to be loaded from database B, table “Env”

I kind of have an idea on how to change the database connection base on the environment, but where would the best place be to place the script that overrides the env reading it from a database?

I know this is Nuxt specific, but that would need to apply for the Env loaded on nuxt.js.

Thanks!

1 Like

Hi @unairubio and welcome to community!

I really don’t have any better idea to create middleware that checks from request and then do env changing in there.
process.env.CHANGE_SOMETHING = “something_new” should work.

Even tho it might break some thing when changing env variables on the fly. Like existing DB connections. I’m not too sure about that one either - have to test and see.

1 Like

Hey @McSneaky, thanks for the reply!

I think it really comes down to; when does Adonis.js resolve the config files? Do they react to Env changes?

I will try putting together a middleware that updates some critical env variable and check the results. Cheers!

This is a really bad idea to do so.

Since Adonis handle request in a concurrent mode you cannot scope a domain/user by changing the global configuration.

What I’ll recommend you to do is to create a middleware that verify the domain and inject into the HttpContext what you need.

2 Likes

Thanks @romain.lanz, I see your point.

The things is, that seems okay for smaller things but I was looking into a way to just change the environment and cascade the application config from there depending on the domain, while keeping a single node process running. I’m guessing it will no be easy to do then?

The other option is simply to Dockerize each instance and have it have different Env. Maybe it’s also the cleanest but the server costs can go up.

You can use containers, for me each app takes about 100mb or RAM (but they are also under quite high load, might be less or more depending on load, not sure)

But maybe there is some better solution for what you are trying to achieve?

What or why is this dynamic env change needed?

1 Like

Yeah, it seems like that’s probably the best approach.

I was simply trying to make sure that the free tier of our application was “cost free” on our end, potentially having all of them on a single process, but I am not going to take this much further.

Thanks for the help guys!