Skip to content

    Frontend System Design

    Runtime Configuration and Environments

    Decide which settings a front end bakes in at build time and which it reads at runtime, so one build can be promoted from staging to production safely.

    By Published 12 min read

    • frontend-system-design
    • configuration
    • environments
    • deployment
    Share

    Standard lessonintermediateFrontend System Design

    Before this: Bundlers and Build Tooling

    What you'll learn: By the end of this lesson you will be able to tell build-time configuration from runtime configuration in a browser app, explain why a build made for staging cannot be promoted to production when its settings are baked in, choose where each kind of value belongs (a constant, a runtime config file, a server, or nowhere in the client), validate configuration at startup, and handle a configuration that fails to load.

    Think of a school uniform versus a name badge. The uniform is made once, in bulk, and looks the same on every pupil. The badge is written on the day and says whose it is. If you print the pupil's name onto the uniform at the factory, every uniform is only good for one pupil. A front-end build is the uniform; the values that differ between environments, such as which API to call, are the badge.

    The running example is the storefront of the ShopStream marketplace: one single-page app that runs in a developer's laptop, in a shared staging environment and in production, and calls a different API host in each.

    The core idea

    1. Configuration is whatever varies between deploys, and code is whatever does not. The Twelve-Factor App states this as a strict separation of config from code, and defines config as everything likely to vary between deploys.
    2. A browser app has two moments when a value can be fixed: when you build it, and when it starts in the user's browser. A value fixed at build time is part of the artifact. A value read at startup is part of the deploy.
    3. Everything in the client is public. Nothing that reaches the browser can be a secret, whichever moment you pick.

    The Twelve-Factor App also describes a build stage, a release stage and a run stage. A release is the output of a build combined with config, every release has a unique ID, and a release cannot be changed once created: any change creates a new release. For a front end, that suggests building once and pairing the same artifact with different config per environment.

    Build time: values baked into the bundle

    Build tools replace references to configuration with literal values while bundling.

    • Vite exposes import.meta.env. Its documentation says these constants are statically replaced at build time to make tree-shaking effective, and that variables prefixed with VITE_ are exposed in client-side source code after bundling. It warns that VITE_* variables should not contain sensitive information such as API keys, because their values end up in the bundle. Built-ins include MODE, BASE_URL, PROD and DEV.
    • Next.js inlines variables prefixed with NEXT_PUBLIC_ into the JavaScript sent to the browser, replacing references with hard-coded values. Its documentation says that after the build the app no longer responds to changes in these variables, and gives the example of building one Docker image and deploying it to several environments: all such variables are frozen at build-time values. It adds that dynamic lookups, such as process.env[varName], are not inlined.

    Two details cause confusion. First, mode and NODE_ENV are different things: Vite's mode controls which .env files load and the value of import.meta.env.MODE, while NODE_ENV is separate, and vite build --mode development still runs with NODE_ENV set to "production". Second, precedence: in Vite, variables already in the process environment when it runs win over .env files, and mode-specific files win over generic ones. A value on a CI runner can therefore silently beat the file you edited. Local .env files are for a developer's machine: Next.js's default template adds them to .gitignore, and its documentation says you almost never want to commit them.

    Build-time values are right for things that really are constants of the artifact: a feature compiled in or out, a release version string, a base path. They are wrong for anything that differs between the environments an artifact is promoted through.

    Illustration 1: the minimal example

    A toy "build" that replaces a placeholder with the value from the environment where it ran. Run in Node:

    const source = 'export const api = "__API_URL__";';
    const build = (env) => source.replace("__API_URL__", env.API_URL);
    
    const artifact = build({ API_URL: "https://api.staging.example.test" });
    console.log("built in staging: ", artifact);
    console.log("promoted to prod: ", artifact);

    Output, from running it in Node 26.13.1:

    built in staging:  export const api = "https://api.staging.example.test";
    promoted to prod:  export const api = "https://api.staging.example.test";

    The artifact carries the staging host. Promoting it changes nothing about its bytes, so production would call staging. The only fix with baked-in values is a second build for production, and then the thing you tested is not the thing you shipped.

    Figure 1. One build or one build per environment

    Build once, configure per environmentSource to Build; Build to One artifact; One artifact to Staging (deploy + config); One artifact to Production (promote + config)Source: one commitSourceone commitBuild: no environment valuesBuildno environmentvaluesOne artifact: same bytesOne artifactsame bytesStaging: its configStagingits configProduction: its configProductionits configdeploy + configpromote + config

    How to read this: the artifact is built once and never touched again. What differs between staging and production is the config delivered next to it, which is the release in Twelve-Factor terms.

    Runtime configuration: values read when the app starts

    Runtime configuration means the artifact asks for its settings when it starts. Next.js says that when you need runtime values in the browser, you set up your own API to provide them to the client, either on demand or during initialization. There are three common ways to deliver them.

    Delivery How Good Watch out for
    A config file served next to the app The app fetches /config.json before rendering Simple; works on any static host An extra request before first render; caching
    Injected into the HTML The server or edge writes the values into the page as it serves it No extra request Needs a server or edge step; inline script and your Content Security Policy
    An endpoint The app calls a small API, often the BFF Can vary per user or tenant A dependency on that API being up

    The Backend for Frontend pattern is covered in BFF: Backend for Frontend, and the policy side in Content Security Policy. Check an injected inline script against your policy before choosing that route.

    Caching the config file

    A config file at a stable URL is the opposite of a hashed asset. MDN defines max-age as how long a response stays fresh, so a long max-age on /config.json would keep users on old settings after you change them. no-cache is the usual fit: MDN says it lets caches store the response but requires validation with the origin before each reuse, and that it does not mean "don't cache" (that is no-store). The hashed bundle can stay cached for a long time because the config no longer lives inside it; see HTTP Caching and Build Performance and Build Caching in this module.

    Figure 2. Startup with runtime config

    sequenceDiagram accTitle: Application startup that fetches and validates runtime configuration accDescr: The browser loads the cached bundle, then requests the configuration file from the static host. The app parses and validates it. If it is valid the app renders. If the request or the validation fails the app shows a clear startup error instead of calling any API. participant B as Browser participant S as Static host B->>S: GET app bundle (cached, hashed name) B->>S: GET config file (revalidated each time) S-->>B: config text Note over B: parse and validate every field alt valid B->>B: render the app with the config else missing, unreachable or invalid B->>B: show a startup error, make no API calls end

    How to read this: the bundle and the config travel separately. Nothing is rendered with a value that has not been checked, so a bad deploy fails loudly at one place.

    Illustration 2: the realistic example

    A startup check for the config file: required keys, no unknown keys, HTTPS only. The error messages are what an on-call engineer will read. Run in Node:

    const KEYS = ["apiBaseUrl", "environment", "flagsUrl"];
    function parseConfig(text) {
      const c = JSON.parse(text);
      const errors = [];
      for (const k of KEYS) if (typeof c[k] !== "string") errors.push(`missing or not a string: ${k}`);
      for (const k of Object.keys(c)) if (!KEYS.includes(k)) errors.push(`unknown key: ${k}`);
      if (typeof c.apiBaseUrl === "string" && !/^https:\/\//.test(c.apiBaseUrl)) errors.push("apiBaseUrl must start with https://");
      if (errors.length) throw new Error(errors.join("; "));
      return Object.freeze(c);
    }
    const good = '{"apiBaseUrl":"https://api.example.test","environment":"production","flagsUrl":"https://flags.example.test"}';
    console.log("good:", parseConfig(good).environment);
    const bad = [
      '{"apiBaseUrl":"http://api.example.test","environment":"production"}',
      '{"apiBaseUrl":"https://api.example.test","environment":"production","flagsUrl":"x","apiSecret":"y"}',
    ];
    for (const text of bad) {
      try {
        parseConfig(text);
      } catch (e) {
        console.log("rejected:", e.message);
      }
    }

    Output, from running it in Node 26.13.1:

    good: production
    rejected: missing or not a string: flagsUrl; apiBaseUrl must start with https://
    rejected: unknown key: apiSecret

    Rejecting unknown keys is deliberate: it catches a key that was added to the file by mistake, including something that looks like a credential. The rule is a convention for this example, not a standard. Freezing the result stops later code from changing a setting by accident. In a real app, validation belongs in one module that every other module imports, so the rest of the code sees a typed object and never reads the raw file.

    Where does each value belong?

    Figure 3. Choosing a home for a value

    flowchart TD accTitle: Choosing where a configuration value should live accDescr: First ask whether the value is a secret. If yes, it must not be in the client at all and belongs on a server. If not, ask whether it differs between environments or must change without a rebuild. If yes, use runtime configuration. If not, it is a build-time constant. A{"Is it a secret?"} -->|"yes"| B["Keep it on a server
    (never in the client)"] A -->|"no"| C{"Does it differ per environment
    or change without a rebuild?"} C -->|"yes"| D["Runtime config
    (file, injected, endpoint)"] C -->|"no"| E["Build-time constant"]

    How to read this: the first question removes values that must not be in a browser. Only the rest are a choice between baked-in and runtime.

    Typical placements for the storefront:

    • API base URL, analytics site ID, environment name: runtime.
    • Release version, build number: build time (they describe the artifact).
    • Third-party API keys that grant access: a server, called through your own endpoint. A publishable key designed to be public is a different case: check the vendor's documentation, and treat it as public.
    • Feature switches that change per user or per minute: not config files at all; see the feature flags lessons in this module.

    Illustration 3: a failure

    The 2 a.m. scenario below combines both failures: a baked-in host that is wrong in production, and a config file that fails to load. The first is shown by Illustration 1. For the second, the sequence in Figure 2 is the design: an app that cannot read its config should say so, rather than guess a default. A default pointing at production is the dangerous one, because a developer's laptop with a broken config would then write to real data.

    Environments: how many, and what is different

    Environments are not a technical concept so much as a risk-management one. Common ones are local development, preview per pull request, shared staging and production. The Twelve-Factor App warns about grouping config into named environments such as staging or qa: it says this does not scale cleanly, because new names are needed as you add deploys. Prefer individual values per deploy over a if (environment === "staging") branch in code. An environment string in the config is useful for labels and monitoring, but code should not switch behaviour on it.

    Keep the set of differences small and written down: the API base, an analytics ID, a flag source, maybe a log level. The more environments differ in behaviour, the less staging tells you about production.

    Trade-offs

    Choice Gain Cost
    Build-time values No startup request, tree-shaking of dead branches One build per environment, or wrong values after promotion
    Runtime config file One artifact for all environments An extra request, a caching rule, a validation step
    Injected into HTML No extra request A server or edge step; inline script policy
    Config from an endpoint Per-user or per-tenant values Another dependency at startup
    Validate at startup Failures are early and readable Code to write and keep in step with the file

    Build it

    This lesson has no lab. The two Node snippets are plain Node and need no install; their output is shown as run. The behaviour of Vite and Next.js comes from their documentation and was not run here, and option names can change between versions. Whether an injected inline script is allowed by a given Content Security Policy was not tested.

    In practice: promoting one build to production

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The ShopStream storefront builds separately for staging and for production, because the API host is read from VITE_API_URL at build time. A release is tested on staging, then rebuilt with production values and deployed. Twice this quarter (illustrative) the production build behaved differently from the one tested: once because a dependency updated between the two builds, once because a variable was missing on the production runner.

    Starting architecture

    Figure 4. A build per environment

    Starting architecture: values baked in per environmentSource to Staging build; Source to Production build; Staging build to Staging; Production build to ProductionSource: same commitSourcesame commitStaging build: API host baked inStaging buildAPI host baked inProduction build: API host baked inProductionbuildAPI host baked inStaging: testedStagingtestedProduction: never tested as builtProductionnever tested asbuilt

    How to read this: the warning boxes show where the problem sits. Production runs bytes that were never tested, because two builds produced two different artifacts.

    Options considered

    Option What it fixes What it costs Risk
    Keep per-environment builds, pin dependencies Reproducible builds Still two artifacts Differences stay possible
    Runtime config file One artifact, tested then promoted Startup request, validation A bad config file at startup
    Inject config into HTML at the edge No extra request Edge logic to maintain Policy and caching interactions

    The decision

    Field Decision record
    Context Two builds per release; production runs an artifact that was never tested.
    Decision Build once with no environment values. Serve /config.json per environment with no-cache. Validate it at startup, fail with a clear error screen, and keep build-time constants only for the release version.
    Consequences, good The tested artifact is the shipped artifact; changing a host needs no rebuild.
    Consequences, bad One request before first render; config must be validated, versioned and reviewed.
    Revisit when Config needs to vary per user or tenant (move to an endpoint) or the startup request shows up as a cost.

    Rollout and verification

    1. List every import.meta.env or process.env use in the client and sort each into the three homes of Figure 3.
    2. Add the config loader and validator in one module; make the rest of the code import its typed result.
    3. Deploy to staging, then promote the same artifact: compare file hashes of the staging and production bundles to confirm they are identical.
    4. Break the config on purpose in staging (remove a key, serve a 404) and confirm the error screen, with no API call made.

    The 2 a.m. failure

    A change to the production config file introduces a typo in apiBaseUrl. Every page shows a startup error, and a status page shows no API failures because the app never called the API.

    First three checks: (1) open the config URL in production and read it; (2) compare it with the last known-good version in source control; (3) check the Cache-Control the file is served with, in case an old copy is still being served or a bad one is cached. Mitigation: restore the previous file. Follow-up: validate the file in CI before deploy, with the same validator the app uses, and alert on startup-error events from the client.

    Architect's notes

    • Build once, promote the artifact. Ask of every value: does it describe the artifact or the deploy?
    • The client is public. A runtime config file is as readable as the bundle.
    • Fail loudly at startup. A default that quietly points at the wrong place is worse than an error screen.
    • Keep the list short. Every extra setting is a combination you did not test.
    • Version the config shape. The app and the file are deployed separately and can disagree.

    Common mistakes

    • Putting a secret in a VITE_ or NEXT_PUBLIC_ variable. It is in the bundle.
    • Rebuilding for each environment and calling the result "the same release".
    • A long max-age on the config file.
    • Defaults that point at production.
    • Reading process.env[name] dynamically and expecting it to be replaced at build time.
    • Switching behaviour on an environment string instead of on specific settings.
    • No validation, so a typo surfaces as a failed API call far from its cause.

    Key takeaways

    • Configuration is what varies between deploys; keep it out of the code and, for a front end, out of the artifact.
    • Build-time values are frozen into the bundle; runtime values are read at startup.
    • Nothing in the browser is secret, so secrets stay on a server.
    • Serve the config file with no-cache and validate it before use.
    • On failure, show a clear startup error rather than guessing a default.

    Practice exercises

    Exercise 1: Starter (30 min). Run the first Node snippet, then change it so the host is read from a config object at call time, and show that two environments now share one artifact.

    Exercise 2: Intermediate (2 hours). Add a rule to parseConfig that flagsUrl must be HTTPS and that a version key is a positive integer, with one rejected example for each.

    Exercise 3: Advanced (half day). For a front end you know, list every environment-dependent value, assign each to a home from Figure 3, and write down what would break if each one were wrong in production.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments