Skip to main content

@rx-angular/isr API

Complete export surface of @rx-angular/isr, split by entry point: @rx-angular/isr/server, @rx-angular/isr/browser, and @rx-angular/isr/models. Every signature is source-derived (package 21.0.1).

Config types: ISRHandlerConfig and its sub-config interfaces (InvalidateConfig, RenderConfig, ServeFromCacheConfig, RouteISRConfig, CacheKeyGeneratorFn, ModifyHtmlCallbackFn) are documented on their own page; see ISR Handler Config.


Server — @rx-angular/isr/server

ISRHandler

The server-side entry point. Instantiated once in your server bundle and wired into three request middlewares: serve-from-cache, render, and invalidate.

class ISRHandler {
constructor(isrConfig: ISRHandlerConfig);

serveFromCache(req: Request, res: Response, next: NextFunction, config?: ServeFromCacheConfig): Promise<Response | void>;

render(req: Request, res: Response, next: NextFunction, config?: RenderConfig): Promise<Response | void>;

invalidate(req: Request, res: Response, config?: InvalidateConfig): Promise<Response>;

getVariantUrlsToInvalidate(urlsToInvalidate: string[]): VariantRebuildItem[];
}

Request, Response, NextFunction are from express.

MemberSignatureReturnsMeaning
constructor(isrConfig: ISRHandlerConfig)ISRHandlerThrows Error('Provide ISRHandlerConfig!') if isrConfig is falsy. Applies defaults (skipCachingOnHttpErrortrue, buildIdnull, invalidateSecretTokennull) and selects the cache handler (config.cache if it is a CacheHandler instance, otherwise a new InMemoryCacheHandler).
serveFromCache(req, res, next, config?: ServeFromCacheConfig)Promise<Response \| void>Looks up the cache key for the request; sends cached HTML if present (regenerating first when revalidate has expired, unless backgroundRevalidation is set). Calls next() on a cache miss or build-id mismatch.
render(req, res, next, config?: RenderConfig)Promise<Response \| void>Renders the page, stores it in cache per the route's revalidate, and sends it. Calls next() on error.
invalidate(req, res, config?: InvalidateConfig)Promise<Response>On-demand cache invalidation. Reads { token, urlsToInvalidate } from the request body; rejects if token !== invalidateSecretToken. Regenerates each URL (including its variants) and returns a JSON summary { status, notInCache, urlWithErrors, invalidatedUrls }.
getVariantUrlsToInvalidate(urlsToInvalidate: string[])VariantRebuildItem[]Expands a list of URLs into the full set of cache keys (base + every configured variant) to be regenerated.

Import

import { ISRHandler } from '@rx-angular/isr/server';

Minimal example

import { ISRHandler } from '@rx-angular/isr/server';
import { CommonEngine } from '@angular/ssr/node';

const isr = new ISRHandler({
indexHtml,
invalidateSecretToken: process.env['ISR_TOKEN'] ?? null,
commonEngine: new CommonEngine(),
browserDistFolder,
bootstrap,
});

server.get('*', (req, res, next) => isr.serveFromCache(req, res, next));
server.get('*', (req, res, next) => isr.render(req, res, next));

provideISR

Registers the environment providers ISR needs on the server (the IsrServerService, the ISR error interceptor provider, and the serialization hook). Activates the ISR service on the server platform only.

const provideISR: () => EnvironmentProviders;
ReturnsMeaning
EnvironmentProvidersProvider bundle for IsrServerService (bound to IsrService), the HTTP error provider, and a BEFORE_APP_SERIALIZED factory that embeds ISR route data into the rendered HTML.

Import

import { provideISR } from '@rx-angular/isr/server';

Minimal example (standalone server config)

import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/ssr';
import { provideISR } from '@rx-angular/isr/server';
import { appConfig } from './app.config';

const serverConfig: ApplicationConfig = {
providers: [provideServerRendering(), provideISR()],
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

isrHttpInterceptors

A ready-made array of ISR HTTP interceptors (HttpInterceptorFn[]), for use with withInterceptors. Currently contains the ISR HTTP-error interceptor, which records failed responses so skipCachingOnHttpError can act on them.

const isrHttpInterceptors: HttpInterceptorFn[]; // = [httpErrorInterceptorISR]

Import

import { isrHttpInterceptors } from '@rx-angular/isr/server';

Minimal example

import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { isrHttpInterceptors } from '@rx-angular/isr/server';

providers: [provideHttpClient(withInterceptors(isrHttpInterceptors))];

IsrServerService

The server-side implementation of IsrServiceInterface (see IsrServiceInterface). Injectable, providedIn: 'root'. On activate() it subscribes to router events, reads the deepest activated route's data, and captures revalidate into ISR state. You normally do not instantiate or inject this directly; provideISR() wires it up and binds it to the IsrService token.

@Injectable({ providedIn: 'root' })
class IsrServerService implements IsrServiceInterface {}

Import

import { IsrServerService } from '@rx-angular/isr/server';

InMemoryCacheHandler

The default cache handler. Stores rendered HTML in an in-process Map. Used automatically when ISRHandlerConfig.cache is not supplied. Cache is lost on server restart.

class InMemoryCacheHandler extends CacheHandler {
constructor();
}

Import

import { InMemoryCacheHandler } from '@rx-angular/isr/server';

FileSystemCacheHandler

A CacheHandler that persists rendered HTML to disk, so the cache survives restarts. Can optionally seed itself from a prerendered-pages folder on startup.

class FileSystemCacheHandler extends CacheHandler {
constructor(options: FileSystemCacheOptions);
}
Constructor paramTypeMeaning
optionsFileSystemCacheOptionsFilesystem cache configuration. Throws Error('Cache folder path is required!') if cacheFolderPath is empty, and throws if addPrerenderedPagesToCache is set without prerenderedPagesPath.

Import

import { FileSystemCacheHandler } from '@rx-angular/isr/server';

Minimal example

import { FileSystemCacheHandler } from '@rx-angular/isr/server';

const cache = new FileSystemCacheHandler({
cacheFolderPath: join(browserDistFolder, 'cache'),
prerenderedPagesPath: browserDistFolder,
addPrerenderedPagesToCache: true,
});

FileSystemCacheOptions

Configuration object for FileSystemCacheHandler.

interface FileSystemCacheOptions {
cacheFolderPath: string;
prerenderedPagesPath?: string;
addPrerenderedPagesToCache?: boolean;
}
FieldTypeDefaultMeaning
cacheFolderPathstring— (required)Directory where cached HTML files are written.
prerenderedPagesPathstringundefinedDirectory to read prerendered pages from on startup. Required when addPrerenderedPagesToCache is true.
addPrerenderedPagesToCachebooleanundefinedWhen true, seeds the cache from prerenderedPagesPath on startup.

Import

import { FileSystemCacheOptions } from '@rx-angular/isr/server';

IsrModule

Legacy NgModule entry point. The NgModule/forRoot() equivalent of provideISR(), kept for applications that have not migrated to a standalone server config. Prefer provideISR in new code.

@NgModule({ providers: [IsrService] })
class IsrModule {
static forRoot(): ModuleWithProviders<IsrModule>;
}

Import

import { IsrModule } from '@rx-angular/isr/server';

Browser — @rx-angular/isr/browser

IsrService

The browser-side base implementation of IsrServiceInterface (see IsrServiceInterface). Injectable, providedIn: 'root'. On the browser it is a no-op token: getState() returns an empty state, and the mutating methods do nothing. It throws if instantiated on the server, where the token is bound to IsrServerService by provideISR() / IsrModule.

@Injectable({ providedIn: 'root' })
class IsrService implements IsrServiceInterface {}

Import

import { IsrService } from '@rx-angular/isr/browser';

Models — @rx-angular/isr/models

All types below are imported from @rx-angular/isr/models.

CacheHandler

Abstract base class every cache handler extends. Implement this to plug in a custom backing store (Redis, etc.).

abstract class CacheHandler {
abstract add(cacheKey: string, html: string, config?: CacheISRConfig): Promise<void>;
abstract get(cacheKey: string): Promise<CacheData>;
abstract has(cacheKey: string): Promise<boolean>;
abstract delete(cacheKey: string): Promise<boolean>;
abstract getAll(): Promise<string[]>;
abstract clearCache?(): Promise<boolean>;
}
MethodSignatureReturnsMeaning
add(cacheKey: string, html: string, config?: CacheISRConfig)Promise<void>Store rendered HTML under cacheKey.
get(cacheKey: string)Promise<CacheData>Retrieve cached data for cacheKey. Rejects if the key is absent.
has(cacheKey: string)Promise<boolean>Whether cacheKey exists.
delete(cacheKey: string)Promise<boolean>Remove cacheKey.
getAll()Promise<string[]>All cache keys currently stored.
clearCache?()Promise<boolean>Optional. Clear the whole cache.

CacheData

The shape stored/returned by a cache handler.

interface CacheData {
html: string;
options: CacheISRConfig;
createdAt: number;
}
FieldTypeMeaning
htmlstringThe rendered HTML.
optionsCacheISRConfigRevalidation/build metadata stored with the entry.
createdAtnumberTimestamp (ms) when the entry was created; used to compute revalidate expiry.

CacheISRConfig (aliased ISROptions)

Per-entry cache metadata. Re-exported under the alias ISROptions.

interface CacheISRConfig {
revalidate: number | null;
buildId?: string | null;
errors?: string[];
}
FieldTypeMeaning
revalidatenumber \| nullRevalidation window for this entry (see RouteISRConfig for value semantics).
buildIdstring \| nullBuild ID the entry was generated under; a mismatch causes the entry to be bypassed.
errorsstring[]Errors captured during generation.

Import

import { CacheISRConfig, ISROptions } from '@rx-angular/isr/models';

RenderVariant

Defines one cache variant: a distinct cached version of a page selected per-request (e.g. logged-in vs. anonymous).

interface RenderVariant {
identifier: string;
detectVariant: (req: Request) => boolean;
simulateVariant?: (req: Request) => Request;
}
FieldTypeMeaning
identifierstringUnique variant name; part of the cache key.
detectVariant(req: Request) => booleanReturns true when this request belongs to the variant. First match wins.
simulateVariant(req: Request) => RequestOptional. Rewrites the request so the variant can be regenerated during on-demand invalidation.

VariantRebuildItem

An expanded rebuild target produced by ISRHandler.getVariantUrlsToInvalidate, one entry per (URL × variant) to regenerate.

interface VariantRebuildItem {
url: string;
cacheKey: string;
reqSimulator: (req: Request) => Request;
}
FieldTypeMeaning
urlstringThe URL to rebuild.
cacheKeystringThe cache key for this URL + variant.
reqSimulator(req: Request) => RequestRequest rewriter (the variant's simulateVariant, or identity for the base).

IsrState

The state object held by the ISR service.

interface IsrState {
revalidate: number | null;
errors: Error[];
extra: Record<string, unknown>;
}
FieldTypeMeaning
revalidatenumber \| nullThe revalidate value captured from the current route's data.
errorsError[]Errors collected during the render (drive skipCachingOnHttpError).
extraRecord<string, unknown>Arbitrary per-render data embedded into the page.

IsrServiceInterface

The contract implemented by both IsrService (browser) and IsrServerService (server).

interface IsrServiceInterface {
getState(): IsrState;
patchState(partialState: Partial<IsrState>): void;
getExtra(): Record<string, unknown>;
activate(): void;
addError(error: Error): void;
addExtra(extra?: Record<string, unknown>): void;
}
MethodSignatureReturnsMeaning
getState()IsrStateCurrent ISR state.
patchState(partialState: Partial<IsrState>)voidMerge a partial into ISR state.
getExtra()Record<string, unknown>The extra bag.
activate()voidBegin listening to router events (server only).
addError(error: Error)voidRecord a render error.
addExtra(extra?: Record<string, unknown>)voidMerge into the extra bag.

Config types

CacheKeyGeneratorFn, InvalidateConfig, ISRHandlerConfig, ModifyHtmlCallbackFn, RenderConfig, RouteISRConfig, and ServeFromCacheConfig are also exported from @rx-angular/isr/models. They are documented in full on the config reference; see ISR Handler Config.


See also