API reference
@push-based/angular-ssr-stream-nestjs API
The API of @push-based/angular-ssr-stream-nestjs: a Nest module that renders every page route, and a Vite plugin for dev.
- Setup
- NestJS
On this page
npm install @push-based/angular-ssr-stream-core@next @push-based/angular-ssr-stream-nestjs@nextThe NestJS module, for @nestjs/platform-express and
@nestjs/platform-fastify. It is built on the Node adapter, and on
Fastify on the Fastify adapter's route handler. It depends on
@push-based/, whose browser providers the app
still needs. It needs @nestjs/common and @nestjs/core 12, and one of
@nestjs/platform-express and @nestjs/platform-fastify 12. On Fastify,
install @push-based/ too: it's an optional peer, loaded
only there, so an Express app installs nothing from Fastify. For the whole
setup, see NestJS.
Two entry points: @push-based/ for the server, and
@push-based/ for the dev server.
AngularStreamModule.forRoot() #
class AngularStreamModule {
static forRoot(options: AngularStreamModuleOptions): DynamicModule;
static forRootAsync(
options: ConfigurableModuleAsyncOptions<AngularStreamModuleOptions, 'create'>,
): DynamicModule;
}
/** The Node adapter's options, unchanged. */
type AngularStreamModuleOptions = NodeHandlerOptions;Renders the Angular application for every GET and HEAD that no controller
answers. The options are those of
createNodeHandler(): rootComponent, config,
allowedHosts, eventDispatchContract, template, staticDir and
trustProxy.
@Module({
imports: [
AngularStreamModule.forRoot({
rootComponent: App,
config,
eventDispatchContract,
allowedHosts: ['localhost', 'my-app.example.com'],
template: new URL('./index.server.html', import.meta.url),
staticDir: new URL('../client/', import.meta.url),
}),
],
controllers: [HelloController],
})
export class AppModule {}When the app initializes, the module adds its render route last: right
before Nest's own 404 and error handlers. On Express, that is one middleware;
on Fastify, a route with the same steps (see On Fastify). That
is after the controllers' routes, and after whatever other modules add when
they initialize (GraphQLModule, and ServeStaticModule on Express),
whichever order Nest runs their onModuleInit hooks in. On Fastify, another
catch-all /* route can't be added at all: Fastify refuses duplicate routes. For each request that reaches it, in
order:
- Under the global prefix (
app.), the request is passed on, so an unknownsetGlobalPrefix('api') /api/...gets Nest's404. The prefix is matched by whole path segments:/apiaryis a page. - A method other than
GETandHEADis passed on, and ends in a 404 unless something after the module takes it. - Under
/assets/, a file instaticDiris served from disk, and anything else is a404, not a page: Vite names those files by their content hash, so a missing one is an old or mistyped URL, such as a chunk from before a deploy. WithstaticDir, the Node adapter's static handler answers it (Not found, in plain text); without it, the module throws aNotFoundException, which Nest's filters answer. - With
staticDir, any other file in it is served from disk. A path that ends in.html, in any case, is left to the renderer, so/,/index.htmland/INDEX.HTMLrender. - Everything else is rendered as a streamed page.
A controller, or a route or middleware another module adds, always answers first, wherever it is mounted: pages are only what is left.
On Fastify#
On @nestjs/platform-fastify, the render route is a Fastify route, GET and
HEAD on /*, which Fastify picks only when no more specific route matches
the URL. A controller's route, or one another module adds, wins whichever
order they were added in. The module adds the route from a plugin that
Fastify loads when the app starts, after every plugin registered before it,
so @fastify/compress applies to pages even when its registration wasn't
awaited. The plugin isn't encapsulated, so the route has Nest's own 404 and
error handlers.
The steps are the ones above, with Fastify's means:
- Under the global prefix, and for a missing file under
/assets/withoutstaticDir, the route callsreply.callNotFound(), which is Nest's404. WithstaticDir, the static handler answers a missing asset, as above. - A method other than
GETandHEADhas no route, and gets Nest's404. - A file in
staticDiris written to the socket by the Node adapter's static handler, and the reply is hijacked:onSendhooks (so@fastify/compress) don't run for it, and headers set withreply.header()aren't sent with it. Register@fastify/staticwithwildcard: falseandglobIgnore: ['**/*.html']instead to compress the files; see Static files. - A page is rendered by the Fastify adapter's
createFastifyHandler(): the status and headers go on the reply, and the body throughreply.send()as a stream, soonSendhooks see it and Fastify logs the request as usual.
Middleware added with app.use() and Fastify onRequest hooks run for
pages; guards, interceptors and pipes don't, as on Express.
What runs for a page#
Pages aren't controller routes, so Nest's guards, interceptors and pipes don't run for them:
- Guards: an auth guard registered as
APP_GUARDprotects the controllers only. Every page stays public. MiddlewareConsumer: middleware applied in a module'sconfigure()doesn't run for pages when the app has a global prefix, sinceforRoutes('*')is then scoped to the prefix. Without a prefix,forRoutes('*')reaches pages too, butforRoutes(never does.SomeController) app.use(): middleware added there runs for every request, pages included, since Express runs it before any route, and Fastify in anonRequesthook.
Anything that must cover pages, such as authentication, sessions or
compression, belongs in app.use().
Exception filters see a page only when it fails before anything has been sent, as below.
Errors#
Before the response has started, an error goes to Nest's exception filters, global filters included:
- A
Hostthat is more than a host name and a port is aBadRequestException(400), from the Node adapter'sBadRequestError. - A host that isn't in
allowedHostsgets403from the renderer, not an exception. - A render that fails before its first byte falls back to a buffered render;
if that fails too, the error reaches the filters as a
500.
Once the shell has been sent, nothing goes back to Nest. An error is logged
([ssr] streaming render failed after commit) and the connection is cut
without the closing chunk, so the client sees a broken response rather than a
complete one, and no filter writes into it. That holds on both platforms.
AngularStreamModule.forRootAsync() #
import type { ConfigurableModuleAsyncOptions } from '@nestjs/common';
// What it comes to, with Options = AngularStreamModuleOptions:
interface ConfigurableModuleAsyncOptions<Options, 'create'> {
imports?: ModuleMetadata['imports'];
useFactory?: (...args: any[]) => Options | Promise<Options>;
inject?: (InjectionToken | OptionalFactoryDependency)[];
useClass?: Type<{ create(): Options | Promise<Options> }>;
useExisting?: Type<{ create(): Options | Promise<Options> }>;
provideInjectionTokensFrom?: Provider[];
}The same module, with the options from a provider, as Nest's
ConfigurableModuleBuilder defines it. The type is Nest's own, from
@nestjs/common; this package exports no name for it.
AngularStreamModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
rootComponent: App,
config: serverConfig,
allowedHosts: config.getOrThrow<string>('ALLOWED_HOSTS').split(','),
template: new URL('./index.server.html', import.meta.url),
staticDir: new URL('../client/', import.meta.url),
}),
}),The options are read once, when the module initializes.
ANGULAR_STREAM_OPTIONS#
const ANGULAR_STREAM_OPTIONS: string | symbol;The injection token the module's options are provided under, whether they came
from forRoot() or forRootAsync():
constructor(@Inject(ANGULAR_STREAM_OPTIONS) options: AngularStreamModuleOptions) {}createRequestListener()#
function createRequestListener(app: INestApplication): NodeHandler;A node:http request listener, (req, res, next?), that hands each request
to the app's Express instance, or to the Fastify instance's router: the server
entry's default export, for angularStreamNest() to
call in vite dev.
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setGlobalPrefix('api');
export default createRequestListener(app);
if (import.meta.env.PROD) {
await app.listen(3000);
}The first request calls app.init(), which registers the routes and the
render route, and on Fastify then starts the instance with ready();
app.listen() does the same in production, and only once. Fastify answers
every request itself, a 404 included, so next is never called there. Vite
rewrites a page request's URL to /index.html before it reaches the listener,
so the listener puts back req.originalUrl, the URL that was asked for, for
Nest to route.
angularStreamNest()#
import { angularStreamNest } from '@push-based/angular-ssr-stream-nestjs/vite';
function angularStreamNest(options?: AngularStreamNestOptions): Plugin[];
/** angularStreamNode()'s options, unchanged. */
interface AngularStreamNestOptions {
/** The server entry, relative to Vite's root. Default: 'src/server.ts'. */
entry?: string;
/** The template, relative to Vite's root. Default: 'index.html'. */
template?: string;
/** Requests for the server entry before Vite sees them: path prefixes, or a function. Default: none. */
routes?: readonly string[] | ((pathname: string, req: IncomingMessage) => boolean);
}The Vite plugins for vite dev:
angularStreamNode(), which streams each page
through the server entry's default export with the dev template, and a
middleware after it that sends that same export every other request Vite has
no file or module for. Without the second, vite dev answers /api/... with
its own 404. That middleware gives a GET or HEAD the dev template too, so
a page fetched without Accept: text/html (curl, fetch(), a link checker)
renders as it does in production. List it before ngp. In a build it does
nothing.
In dev, an edit to the server runs the entry again, which creates a new Nest
app. To close the old one, so its onModuleDestroy hooks run, accept the
update in the entry and close the app when it is disposed:
import.meta.hot?.accept();
import.meta.hot?.dispose(() => app.close());Static files#
Three ways to serve the browser build, dist/client:
staticDir: served by the render route, after the controllers. Paths ending in.htmlare left to the renderer, so/and/index.htmlboth render. This is the one to use unless something else serves the files.app.: Express's static middleware, registered when it is called, before every route. LeaveuseStaticAssets( dir, { index: false }) staticDirout. Withoutindex: false,/gets the browser build's unrenderedindex.html;/index.htmlgets it either way.ServeStaticModulefrom@nestjs/serve-static: by default it answers everyGETthat isn't a file withindex.html, so nothing is rendered. Turn that off withexclude: ['/{*any}']and passserveStaticOptions: { index: false }. Where it is imported doesn't matter: its middleware always comes before the render route. Express only: on Fastify it always adds aGET *route, and the app fails to start withFST_ERR_DUPLICATED_ROUTE.
In each case a missing file under /assets/ is a 404.
On Fastify, staticDir works the same, but files from it skip
@fastify/compress (see On Fastify). The alternative is
@fastify/static, registered with wildcard: false, since its default
GET /* route makes the app fail to start (FST_ERR_DUPLICATED_ROUTE), and
globIgnore: ['**/*.html'], so that / and /index.html render. Nest's
app.useStaticAssets() registers the same plugin, though its options type
lacks globIgnore.
Decorators#
The package is published without decorators: the module is a
ConfigurableModuleBuilder class, and its one provider a factory. It works
whatever compiles the app's own decorators. The app's controllers and
services need experimentalDecorators and emitDecoratorMetadata, which
Vite's transform reads from the tsconfig; see
TypeScript.
Other platforms#
On an HTTP adapter other than Express and Fastify, the module throws when the app initializes:
[angular-ssr-stream] AngularStreamModule renders pages on @nestjs/platform-express or @nestjs/platform-fastify; this application runs on '<type>'.An application context (NestFactory.) has no HTTP
adapter, and the module does nothing there.