Skip to content

FastifyStaticOptions

reference
1 min readUpdated

Kind: Interface

Source: packages/platform-fastify/interfaces/external/fastify-static-options.interface.ts

Part of: Platform Fastify

FastifyStaticOptions configures static asset serving for the Fastify platform adapter. It controls the asset root directory, URL prefix, reply decoration, caching headers, redirects, directory listings, and wildcard route behavior when registering static-file support.

Properties

PropertyType
root`string
prefixstring
prefixAvoidTrailingSlashboolean
serveboolean
decorateReplyboolean
schemaHideboolean
setHeaders(res: SetHeadersResponse, path: string, stat: Stats) => void
redirectboolean
wildcardboolean
list`boolean
allowedPath( pathName: string, root: string, request: FastifyRequest, ) => boolean
preCompressedboolean
acceptRangesboolean
cacheControlboolean
dotfiles`'allow'
etagboolean
extensionsstring[]
immutableboolean
index`string[]
lastModifiedboolean
maxAge`string
constraintsRouteOptions['constraints']

Diagram

mermaid
graph LR
  A[FastifyStaticOptions] --> B[root]
  A --> C[prefix]
  A --> D[Serving behavior]
  A --> E[Response behavior]
  A --> F[Directory listing]

  D --> D1[serve]
  D --> D2[redirect]
  D --> D3[wildcard]

  E --> E1[decorateReply]
  E --> E2[schemaHide]
  E --> E3[setHeaders]

  F --> F1[list]

Usage

ts
import { join } from 'node:path';
import type { FastifyStaticOptions } from './interfaces/external/fastify-static-options.interface';

const staticOptions: FastifyStaticOptions = {
  root: join(process.cwd(), 'public'),
  prefix: '/assets/',
  prefixAvoidTrailingSlash: false,
  serve: true,
  decorateReply: true,
  schemaHide: true,
  redirect: true,
  wildcard: true,
  list: false,
  setHeaders(res, path, stat) {
    if (path.endsWith('.js') || path.endsWith('.css')) {
      res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
    }

    res.setHeader('Content-Length', stat.size);
  },
};

// Example: pass staticOptions when configuring Fastify static serving.

AI Coding Instructions

  • Use an absolute filesystem path for root; provide an array of roots only when serving assets from multiple locations.
  • Keep prefix aligned with application routing conventions, including whether a trailing slash is expected.
  • Use setHeaders for cache and content-related headers; avoid performing asynchronous work in this callback.
  • Disable decorateReply only if application code does not need Fastify reply helpers for static files.
  • Enable list only for controlled or development environments, as directory listings can expose file names and structure.

Was this page helpful?

Download as PDF
FastifyStaticOptions — NestJS head-to-head