nestjs/serve-static
Serve static websites (SPA's) using Nest framework (node.js) 🥦
A progressive Node.js framework for building efficient and scalable server-side applications.
@nestjs/serve-static package for Nest, useful to serve static content like Single Page Applications (SPA). However, if you are building MVC application or want to serve assets files (images, docs), use the useStaticAssets() method (read more here) instead.
$ npm i --save @nestjs/serve-static
This package ships as ES modules only and requires Node.js ^20.19.0 || ^22.12.0 || >=23.0.0.
CommonJS applications can still consume it through Node's require(esm) support. TypeScript projects that compile to CommonJS need "module": "nodenext" in their tsconfig.json; the older "node16" setting predates require(esm) and reports TS1479.
See full example here.
Used by 5 tracked packages
Simply import ServeStaticModule in your Nest application.
import { Module } from '@nestjs/common';
import { join } from 'path';
import { ServeStaticModule } from '@nestjs/serve-static';
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(import.meta.dirname, '..', 'client')
})
]
})
export class ApplicationModule {}
The forRoot() method takes an options object with a few useful properties.
| Property | Type | Description |
|---|---|---|
rootPath | string | Static files root directory. Default: "client" |
serveRoot | string | Root path under which static app will be served. Default: "" |
renderPath | string / RegExp | Path to render static app (concatenated with the serveRoot value). Default: * (wildcard - all paths). Note: RegExp is not supported by the @nestjs/platform-fastify. |
exclude | string[] / RegExp | Paths to exclude when serving the static app, given either as an array of path patterns or as a single RegExp matched against the request path. WARNING! Not supported by fastify. If you use fastify, you can exclude routes using regexp (set the renderPath to a regular expression) instead. |
serveStaticOptions | Object | Serve static options (static files) |
useGlobalPrefix | boolean | If true, static app will be prefixed by the global prefix set through setGlobalPrefix(). Default: false https://docs.nestjs.com/faq/global-prefix |
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.
Nest is MIT licensed.