Single-Page Apps – Using SPA in Production with Separate Configuration

bundlingdeploymentdesignsingle-page-appsweb-development

Problem statement

dev team

Dev team wants to pre-build the SPA's (Angular App & React App) and provide single package containing JS, CSS, & HTML file. There's no server-side rendering / lazy loading also. Hence, configurations like service URL, app settings etc. have to be a build parameters. And expects DevOps team to build & deploy different builds for each environment for production as well.

DevOps team

DevOps teams wants to have a single build in QA environment and push the files to Prod, after completing testing. While moving to Prod, only configs can be changed, but all the built code should be same. If any new build is done, it is considered as untested code and hence unfit for production.

Archs

The configs have to be secure & users should not be able to easily read / modify it. Also, site will also be provided with http, hence using cookies or headers might not be a suitable option.

Is there any way to have configuration & application code be separated in an SPA?

Similar Questions:

  1. How to configure a SPA on loading?

  2. SPA javascript configuration file

Best Answer

You are completely right that it should be the same artifacts that are deployed to all environments. Especially in npm, dependencies tend to be loosely defined so a updated dependency could easily break the build just by building at different times. Even if you don't use hat or tilde in packages.json transient dependencies could be less strict with versioning.

What is suggested in the other answer regarding dotenv will not work unless you combine it with #2 og #3 from this answer.

Basically you have a few options.

  1. Switch on the url in order to find the current environment you are in. This is a complete hack. Do not do this!!

  2. Have some server side code replace global vars in index.html on each request. The simplest solution depends on what you have installed on your server. It could be php or even something simple as SSI if you are on IIS. You will want to keep you index.html as valid html so you still can do local development. SSI is nice in this regard since it works inside comments. If you do php, keep your index.html and make a index.php which reads index.html but replaces your vars. A html parser works well for this replacement.

  3. Setup your release to generate a transformed index.html from the index.html created during build. This transformed index contains a snapshot of variables for a given environment when release is run on the environment.

If your needs are simply configuration variables, I would recommend #3. If you need something a little more advanced, go for #2.