← Back to Angular, page 5

angular-0085 · Hard senior

How do you design provide* functions for a library or feature, and how do you load runtime configuration before the app starts?

A provide function returns EnvironmentProviders built with makeEnvironmentProviders, so consumers add one call to their config. For runtime configuration, load a config file with provideAppInitializer before bootstrap completes and expose it through a service. This lets one build run in many environments, unlike fileReplacements, which bakes values in at build time.

Full answer

Modern Angular libraries and features expose a function such as provideRouter(...) or provideHttpClient(...), not a module with forRoot().

Writing a provide function:

  • Return EnvironmentProviders from makeEnvironmentProviders([...]). This type cannot be placed in a component's providers by mistake, which prevents a common error.
  • Take options as parameters, with defaults.
  • Support optional features with a features pattern: small functions (withLogging()) that return objects with providers, as provideHttpClient(withInterceptors(...)) does. Features keep the core small and tree-shakeable.
  • Use InjectionToken with a factory for defaults that work without any provider.

Configuration approaches:

  1. Build-time: fileReplacements in angular.json swaps environment.ts per configuration. Simple and fully typed, but you need one build per environment, and the same artifact cannot move from staging to production.
  2. Runtime: ship one build, and load /config.json (written by the deployment) at start-up. This follows the "build once, deploy many" rule and lets operations change API URLs without a rebuild.

Loading at start-up: provideAppInitializer(() => inject(ConfigService).load()) runs in an injection context before the app is considered started. If the function returns a Promise or an Observable, Angular waits for it. This replaces the older APP_INITIALIZER token with multi: true. Router initial navigation, and rendering, do not start until the work is done, so keep it fast and add a timeout. A failure blocks start-up, so decide on a fallback (default config, or an error page).

Rules: never put secrets in runtime config files (they are public). Validate the loaded object (a hand-written check or a schema library). Keep the config in a signal so features can read it with computed. Exposing it as a token (APP_CONFIG) with useFactory: () => inject(ConfigService).config() is another option, but it fails if read before loading, so the service approach with a clear error is safer.

typescript
// file: config.service.ts
import { EnvironmentProviders, Injectable, computed, inject, makeEnvironmentProviders, provideAppInitializer, signal } from '@angular/core';

export interface AppConfig {
  apiBaseUrl: string;
  features: Record<string, boolean>;
}

const DEFAULT_CONFIG: AppConfig = { apiBaseUrl: '/api', features: {} };

function isAppConfig(value: unknown): value is AppConfig {
  const v = value as Partial<AppConfig> | null;
  return typeof v === 'object' && v !== null && typeof v.apiBaseUrl === 'string' && typeof v.features === 'object';
}

@Injectable({ providedIn: 'root' })
export class ConfigService {
  private readonly state = signal<AppConfig | null>(null);

  readonly config = computed(() => {
    const value = this.state();
    if (!value) {
      throw new Error('Config is not loaded yet');
    }
    return value;
  });

  async load(url: string, timeoutMs = 3000): Promise<void> {
    try {
      const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
      const body: unknown = await response.json();
      if (!response.ok || !isAppConfig(body)) {
        throw new Error('Invalid config');
      }
      this.state.set(body);
    } catch {
      this.state.set(DEFAULT_CONFIG); // fallback so the app can still start
    }
  }
}

export interface ConfigFeature {
  url: string;
}

export function withConfigUrl(url: string): ConfigFeature {
  return { url };
}

export function provideAppConfig(...features: ConfigFeature[]): EnvironmentProviders {
  const url = features[0]?.url ?? '/config.json';
  return makeEnvironmentProviders([provideAppInitializer(() => inject(ConfigService).load(url))]);
}

// file: config.service.spec.ts
import { ApplicationInitStatus } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ConfigService, provideAppConfig, withConfigUrl } from './config.service';

describe('provideAppConfig', () => {
  afterEach(() => {
    (window.fetch as jasmine.Spy).and?.callThrough?.();
  });

  it('loads the config before the app is initialised', async () => {
    spyOn(window, 'fetch').and.resolveTo(
      new Response(JSON.stringify({ apiBaseUrl: 'https://api.example.com', features: { beta: true } })),
    );
    TestBed.configureTestingModule({ providers: [provideAppConfig(withConfigUrl('/config.json'))] });
    await TestBed.inject(ApplicationInitStatus).donePromise;

    expect(TestBed.inject(ConfigService).config().apiBaseUrl).toBe('https://api.example.com');
  });

  it('falls back to defaults when the request fails', async () => {
    spyOn(window, 'fetch').and.rejectWith(new Error('network down'));
    TestBed.configureTestingModule({ providers: [provideAppConfig()] });
    await TestBed.inject(ApplicationInitStatus).donePromise;

    expect(TestBed.inject(ConfigService).config().apiBaseUrl).toBe('/api');
  });
});

Angular 20.3, strict check passes, and a Karma spec runs the initializer against a stubbed `fetch` and checks the loaded value and the failure path.

Key points

  • Return `EnvironmentProviders` from `makeEnvironmentProviders`. Use feature functions for options.
  • Build-time `fileReplacements` is typed but needs a build per environment.
  • Runtime config with `provideAppInitializer` supports build once, deploy many.
  • Validate config, add a timeout and a fallback, and never store secrets in it.

Common mistakes

  • Putting secrets in `environment.ts` or `config.json`. Both are public.
  • Letting a slow config request delay the whole start-up with no timeout.
  • Reading the config before it loads, for example in a module-level constant.

Follow-ups

  • How does `provideAppInitializer` differ from `APP_INITIALIZER`?
  • How would you keep config loading from delaying the first paint with SSR?
  • How do you test a function that calls `provideAppInitializer`?

Tips

  • Contrast the two configuration styles, and say which you choose and why.
  • Mention `EnvironmentProviders` and what it protects against.
  • Say clearly that front-end config is never secret.

Evaluation rubric

  • Designs provide functions and features correctly.
  • Explains runtime versus build-time configuration with trade-offs.
  • Handles failure, validation, and security.