# Platform decisions — auth, config, errors, i18n, UI library, micro-frontends

The five or six things an Angular app has exactly one of. Decide each once, write it into `ARCHITECTURE.md`, and provide it in `app.config.ts`. Verified 2026-09 against https://angular.dev/api/core/provideAppInitializer, https://angular.dev/api/core/provideBrowserGlobalErrorListeners, https://learn.microsoft.com/entra/msal/javascript/angular/configuration and https://angular.dev/guide/i18n.

## 1. Authentication

| Situation | Choice |
|---|---|
| Identity provider is Microsoft Entra ID | `@azure/msal-angular` + `@azure/msal-browser` |
| Any other OIDC provider (Keycloak, Auth0, Okta, Ping) | `angular-auth-oidc-client` |
| Tokens must never reach the browser (regulated data, long-lived refresh) | Backend-for-frontend: same-site `HttpOnly` cookies, the SPA never sees a token |

Whatever the library, the shape is the same: **one** place acquires tokens, **one** interceptor attaches them, **one** guard protects routes. Do not let feature code call the auth library.

MSAL with standalone bootstrap — factory providers in `app.config.ts`, exactly as the MSAL docs show:

```ts
// app.config.ts (excerpt)
import type { ApplicationConfig } from '@angular/core';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import {
  MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG,
  MsalBroadcastService, MsalGuard, MsalInterceptor, MsalService,
  type MsalGuardConfiguration, type MsalInterceptorConfiguration,
} from '@azure/msal-angular';
import { BrowserCacheLocation, InteractionType, PublicClientApplication, type IPublicClientApplication } from '@azure/msal-browser';

export function msalInstanceFactory(): IPublicClientApplication {
  return new PublicClientApplication({
    auth: { clientId: '<client-id>', authority: '<authority-url>', redirectUri: '/', postLogoutRedirectUri: '/' },
    cache: { cacheLocation: BrowserCacheLocation.LocalStorage },
  });
}
export function msalGuardConfigFactory(): MsalGuardConfiguration {
  return { interactionType: InteractionType.Redirect, authRequest: { scopes: ['user.read'] }, loginFailedRoute: '/login-failed' };
}
export function msalInterceptorConfigFactory(): MsalInterceptorConfiguration {
  return { interactionType: InteractionType.Redirect, protectedResourceMap: new Map([['/api/', ['api://<app-id-uri>/access']]]) };
}

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptorsFromDi()),
    { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true },
    { provide: MSAL_INSTANCE, useFactory: msalInstanceFactory },
    { provide: MSAL_GUARD_CONFIG, useFactory: msalGuardConfigFactory },
    { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: msalInterceptorConfigFactory },
    MsalService, MsalGuard, MsalBroadcastService,
  ],
};
```

`MsalInterceptor` is a class interceptor, so it needs `withInterceptorsFromDi()` alongside any functional interceptors you register with `withInterceptors([...])`. Protect routes with `canActivate: [MsalGuard]`; with redirect interaction also bootstrap `MsalRedirectComponent`.

**Authorisation** is a server decision. The client hides what the user cannot do; it never *is* the check. Keep role/permission logic in one `computed()` on the auth store so a change lands in one file.

## 2. Runtime configuration

One artifact, every environment. Build-time replacement (`fileReplacements`) means one build per environment, which means the thing you tested is not the thing you shipped.

```ts
// core/config/app-config.ts
import { InjectionToken, inject, provideAppInitializer, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';

export type AppConfig = { apiBaseUrl: string; environment: 'dev' | 'test' | 'prod'; features: Record<string, boolean> };

const state = signal<AppConfig | null>(null);
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG', {
  providedIn: 'root',
  factory: () => {
    const config = state();
    if (!config) throw new Error('APP_CONFIG read before provideAppInitializer completed');
    return config;
  },
});

export const provideAppConfig = () =>
  provideAppInitializer(async () => {
    state.set(await firstValueFrom(inject(HttpClient).get<AppConfig>('/config.json')));
  });
```

`provideAppInitializer(fn)` replaces the deprecated `APP_INITIALIZER` token; returning a promise blocks bootstrap until it settles. Serve `config.json` with `Cache-Control: no-cache` so a deploy takes effect immediately.

**Nothing secret goes in it.** Everything the browser downloads is public — API keys, client secrets and connection strings belong behind your own backend. A "public" key that gates billing is not public.

## 3. Error handling and monitoring

```ts
// app.config.ts (excerpt)
import { ErrorHandler, provideBrowserGlobalErrorListeners } from '@angular/core';
import { GlobalErrorHandler } from './core/errors/global-error-handler';

providers: [
  provideBrowserGlobalErrorListeners(),
  { provide: ErrorHandler, useClass: GlobalErrorHandler },
];
```

`provideBrowserGlobalErrorListeners()` forwards `window` `error` and `unhandledrejection` events into Angular's `ErrorHandler`, so the custom handler is the one funnel for everything. In the handler: report to monitoring with a correlation id, show one user-facing message, and never swallow silently. Separate *expected* failures (a 404 for a deleted order — the page renders an empty state) from *unexpected* ones (a 500 — the handler reports it); only the second class belongs in monitoring, or the signal drowns in noise.

HTTP errors get normalised in one functional interceptor into a single `AppError` shape before they reach features, so no component parses `HttpErrorResponse` bodies.

## 4. Internationalisation

| Need | Choice | Cost |
|---|---|---|
| A fixed set of locales, no in-app switching, best runtime | `@angular/localize` (`i18n` attributes, `$localize`) — one build per locale | Build matrix, deploy per locale |
| User switches language without a reload; content arrives from a CMS | A runtime library (Transloco, `ngx-translate`) | One extra HTTP request, translations not type-checked |

Decide before the first user-facing string is written; retrofitting either one across a grown app is a multi-week change. Whichever you pick: never concatenate translated fragments, always use ICU plurals and `select`, and format dates, numbers and currency with `Intl`/Angular pipes rather than hand-rolled strings.

## 5. UI library

| Situation | Choice |
|---|---|
| Default — internal app, speed matters, Material Design is acceptable | Angular Material + CDK (Material 3 token theming) |
| Bespoke design system, your own visuals, accessibility must not be rebuilt | `@angular/aria` headless directives (Combobox, Listbox, Select, Menu, Tabs, Tree, Grid, Accordion, Toolbar…) plus CDK overlay/a11y/drag-drop |
| Data-grid-heavy back office (pivot, inline edit, frozen columns, export) | PrimeNG, or a dedicated grid, scoped to those screens only |

Build tokens and primitives (`shared/ui`) before features, not after: a design system extracted from six inconsistent features is a rewrite. Whatever the base, wrap third-party components in your own `shared/ui` component so a swap is one folder, not 300 templates.

## 6. Micro-frontends

Split deployables only when teams must **release on different days**. If the pain is "our folders are a mess" or "builds are slow", fix module boundaries and use Nx affected builds — both are far cheaper than distributed versioning.

When the release-cadence reason genuinely holds, use Native Federation (`@angular-architects/native-federation`), which works with the esbuild-based `@angular/build:application` builder. Then decide and write down, before the first split: who owns the shell, how Angular and RxJS versions stay aligned across remotes, how auth state is shared, how a remote that fails to load degrades, and how the whole thing is tested end to end. If those five answers do not exist yet, do not split.
