Conceptualizing How a Modern Single Page App is Served
I’ve noticed some confusion in how Single Page Applications are served among developers who are new to these apps. This post is a short explanation of how a Single Page Application gets from the web server to a user’s web browser.
All the examples I show in this post show builders that are only for testing purposes. While the builder pattern can be used in production code, the builders shown below are not appropriate for production code because they contain pre-canned default values. Leave these in your test suite.
It's not magic, you just don't understand it yet
Dev 1: “Wait, how did it do that?”
Dev 2: “I have not clue, it’s Spring* magic.”
Dev 1: “Oh well, as long as it just works!”
* substitute Spring for any library or framework
Every time I hear (or, admittedly, say) something like this, I cringe.
When we refer to code as magic, we perpetuate the mindset that some code is unaccessible. That we don’t need to know how something works, only that is does work. This is not the mindset of a true craftsman. A craftsman seeks to understand the tools she uses, because she knows that she will be able to use them more effectively, and will be more able to deal with inevitable failures.
Updated 2017-02-12: Added a strategy for loading configuration at initial page load, using an “env.js” file.
Recently, I needed to inject some configuration variables into my client-side app. Because Googling for it turned up a lot of “well, you could maybe do this…” I decided to write down what I see as the 3 main options:
- Best in show: Load configuration at run time.
- Prize for simplest solution: Build your application with configuration variables as constants at compile time.
- Runner up: Use server-side templating to inject configuration at render time.