Sharing Angular Components Across CSR and SSR Projects with the Strategy Pattern
How we used Angular's DI system and the strategy pattern to share an HLS audio player between a CSR dashboard and an SSR app with fundamentally different auth architectures.
Sharing Angular Components Across CSR and SSR Projects with the Strategy Pattern
We recently hit a problem that’s probably familiar to anyone managing multiple Angular apps from a shared library: a component that works perfectly in one app breaks in another because of how authentication works.
Our shared UI library has an audio Player component that streams HLS content. It worked great in our client-side rendered (CSR) dashboard app, where the browser has direct access to auth tokens. Then we needed the same Player in our server-side rendered (SSR) app — where tokens never reach the browser at all.
Here’s how the original AudioService loaded HLS streams:
@Injectable({providedIn: 'root'})
export class AudioService {
private readonly authService = inject(AUTH_SERVICE);
load(hlsManifestUrl: string): void {
this.destroy();
const token = this.authService.getAccessToken();
if (Hls.isSupported()) {
this.hls = new Hls({
xhrSetup: (xhr, url) => {
if (url.includes('/keys/') && token) {
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
}
}
});
this.hls.loadSource(hlsManifestUrl);
this.hls.attachMedia(this.audio);
}
}
}
The service grabs an access token and attaches it as a Bearer header to HLS encryption key requests. Simple and effective — until you need it somewhere the token doesn’t exist.
The Two Worlds
In our CSR dashboard, authentication is straightforward. The browser authenticates via OIDC, holds the token in memory, and attaches it to API requests directly. getAccessToken() returns a string. Done.
Our SSR app uses the Backend-for-Frontend (BFF) pattern. The browser never sees a token. Instead:
- The browser holds a session cookie
- All API requests go through an Express proxy layer
- The proxy resolves the session, retrieves the token from server-side storage, and attaches it before forwarding to the upstream API
This is a fundamentally different auth architecture. There’s no token to call getAccessToken() with.
Why Not Just if (isPlatformBrowser)?
The first instinct might be to add a platform check:
// Don't do this
if (isPlatformBrowser(this.platformId)) {
// attach token directly
} else {
// do something else?
}
This doesn’t solve the problem. The issue isn’t server vs. browser rendering — HLS playback only happens in the browser regardless. The issue is that in the SSR app’s browser, the token doesn’t exist. Platform checks can’t conjure a token out of thin air.
Beyond that, scattering auth-awareness throughout shared components violates single responsibility. Your audio service shouldn’t know about proxy routing, session cookies, or BFF architectures. And platform checks are notoriously hard to test.
The Strategy Pattern with Angular DI
The solution is to extract the auth concern into an interface and let each app provide its own implementation via dependency injection.
export interface HlsAuthStrategy {
/** Configure XHR headers for auth on key requests */
configureXhr(xhr: XMLHttpRequest, url: string): void;
/** Optionally rewrite a URL before HLS.js fetches it */
rewriteUrl?(url: string): string;
}
export const HLS_AUTH_STRATEGY =
new InjectionToken<HlsAuthStrategy>('HLS_AUTH_STRATEGY');
The interface captures exactly two things the auth layer needs to do:
configureXhr: Set headers on outgoing requests (e.g.,Authorizationor proxy-related headers)rewriteUrl(optional): Rewrite URLs before HLS.js fetches them (e.g., redirect through a proxy)
rewriteUrl is optional because only the proxy strategy needs URL rewriting. The bearer token strategy talks directly to the API.
The refactored AudioService is now auth-agnostic:
@Injectable({providedIn: 'root'})
export class AudioService {
private readonly hlsAuthStrategy = inject(HLS_AUTH_STRATEGY);
load(hlsManifestUrl: string): void {
this.destroy();
const strategy = this.hlsAuthStrategy;
if (Hls.isSupported()) {
this.hls = new Hls({
xhrSetup: (xhr, url) => strategy.configureXhr(xhr, url),
...(strategy.rewriteUrl
? {urlRewriter: (url: string) => strategy.rewriteUrl!(url)}
: {}),
});
this.hls.loadSource(hlsManifestUrl);
this.hls.attachMedia(this.audio);
}
}
}
No tokens, no auth imports, no platform checks. The service doesn’t know or care how authentication works.
Bearer Token Strategy (CSR)
For the CSR app, the strategy is a thin wrapper around what we had before:
@Injectable()
export class BearerTokenHlsAuthStrategy implements HlsAuthStrategy {
private readonly authService = inject(AUTH_SERVICE);
configureXhr(xhr: XMLHttpRequest, url: string): void {
const token = this.authService.getAccessToken();
if (url.includes('/keys/') && token) {
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
}
}
}
Same behavior, just extracted. The AUTH_SERVICE dependency now lives here — in the CSR-specific strategy — instead of in the shared service.
Wire it in the CSR app’s config:
// app.config.ts (CSR app)
providers: [
{provide: HLS_AUTH_STRATEGY, useClass: BearerTokenHlsAuthStrategy},
]
Proxy Strategy (SSR + BFF)
For the SSR app, the strategy rewrites key URLs to go through the BFF proxy and sets the headers the proxy expects:
@Injectable()
export class ProxyHlsAuthStrategy implements HlsAuthStrategy {
configureXhr(xhr: XMLHttpRequest, url: string): void {
if (url.includes('/keys/')) {
xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.setRequestHeader('x-proxy-target', 'api');
}
}
rewriteUrl(url: string): string {
if (!url.includes('/keys/')) return url;
const parsed = new URL(url);
return `/proxy${parsed.pathname}${parsed.search}`;
}
}
Instead of attaching a Bearer token (which doesn’t exist in the browser), this strategy:
- Rewrites the URL — HLS.js requests
/proxy/keys/abc123instead ofhttps://api.example.com/keys/abc123 - Sets proxy headers — The CSRF header and a routing header that tells the proxy which upstream to forward to
- Relies on cookies — The session cookie is sent automatically by the browser. The proxy resolves it to a token server-side.
The browser never sees a token. The proxy does all the heavy lifting.
Wire it in the SSR app’s config:
// app.config.ts (SSR app)
providers: [
{provide: HLS_AUTH_STRATEGY, useClass: ProxyHlsAuthStrategy},
]
Applying the Pattern Again: Play History Beacons
Once we had this pattern, we noticed a second auth concern in the Player: recording play history on page unload.
The PlayHistoryService used navigator.sendBeacon for reliability during unload, with a sync XHR fallback. The problem was the same — the fallback needed a Bearer token for the CSR app, but needed proxy routing for the SSR app.
We applied the exact same pattern:
export interface PlayRecordStrategy {
sendBeacon(url: string, body: string): void;
}
export const PLAY_RECORD_STRATEGY =
new InjectionToken<PlayRecordStrategy>('PLAY_RECORD_STRATEGY');
The CSR implementation uses navigator.sendBeacon with a sync XHR fallback. The SSR implementation routes through the proxy via sync XHR (since sendBeacon can’t set custom headers):
// SSR proxy implementation
@Injectable()
export class ProxyPlayRecordStrategy implements PlayRecordStrategy {
sendBeacon(url: string, body: string): void {
try {
const parsed = new URL(url);
const proxyUrl = `/proxy${parsed.pathname}`;
const xhr = new XMLHttpRequest();
xhr.open('POST', proxyUrl, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.setRequestHeader('x-proxy-target', 'api');
xhr.send(body);
} catch (e) {
console.error('[PlayRecord] Proxy beacon failed:', e);
}
}
}
The PlayHistoryService becomes dead simple:
recordPlayBeacon(request: RecordPlayRequest): void {
const url = `${this.apiBaseUrl}/plays`;
const body = JSON.stringify(request);
this.playRecordStrategy.sendBeacon(url, body);
}
No tokens, no auth logic, no platform checks. The service delegates to whatever strategy the host app provides.
Wiring It All Together
Here’s the satisfying part — the two app configs side by side:
// CSR app
providers: [
{provide: HLS_AUTH_STRATEGY, useClass: BearerTokenHlsAuthStrategy},
{provide: PLAY_RECORD_STRATEGY, useClass: BearerTokenPlayRecordStrategy},
]
// SSR app
providers: [
{provide: HLS_AUTH_STRATEGY, useClass: ProxyHlsAuthStrategy},
{provide: PLAY_RECORD_STRATEGY, useClass: ProxyPlayRecordStrategy},
]
Two lines per app. The shared Player component, its state management, and all supporting services are completely unchanged. No conditional logic. No isPlatformBrowser. No environment.isSSR flags.
Testing Gets Easier Too
A nice side effect: testing becomes trivial. Instead of mocking an entire auth system, you mock a two-method interface:
describe('AudioService', () => {
let mockStrategy: HlsAuthStrategy;
beforeEach(() => {
mockStrategy = { configureXhr: vi.fn() };
TestBed.configureTestingModule({
providers: [
AudioService,
{provide: HLS_AUTH_STRATEGY, useValue: mockStrategy},
],
});
});
// Tests focus on behavior, not auth plumbing
});
Each strategy implementation is independently testable too — pure logic with no DI complexity:
describe('ProxyHlsAuthStrategy', () => {
it('should rewrite /keys/ URLs to proxy path', () => {
const strategy = new ProxyHlsAuthStrategy();
const result = strategy.rewriteUrl('https://api.example.com/keys/abc123');
expect(result).toBe('/proxy/keys/abc123');
});
it('should leave non-key URLs unchanged', () => {
const strategy = new ProxyHlsAuthStrategy();
const url = 'https://cdn.example.com/segment-001.ts';
expect(strategy.rewriteUrl(url)).toBe(url);
});
});
When to Reach for This Pattern
This approach works well when:
- Same component, different auth architectures — CSR with direct tokens vs. SSR with BFF proxy vs. mobile with refresh tokens
- Same service, different transport mechanisms — direct API calls vs. proxy routing vs. WebSocket channels
- You’re tempted to add platform checks inside a shared library — that’s the smell. Extract a strategy instead.
The key principle: components shouldn’t know how they’re authenticated. Auth is an infrastructure concern. When you push it to the edges via DI, your shared code stays clean, testable, and reusable across any architecture.