or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

directory-listing.mdindex.mdplugin-registration.mdreply-decorators.md
tile.json

tessl/npm-fastify--static

Plugin for serving static files as fast as possible.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@fastify/static@8.2.x

To install, run

npx @tessl/cli install tessl/npm-fastify--static@8.2.0

index.mddocs/

@fastify/static

@fastify/static is a Fastify plugin that provides high-performance static file serving capabilities for Fastify web applications. It offers comprehensive functionality for serving static assets including support for directory listings, custom root paths, prefix routing, host constraints, content encoding negotiation (gzip, brotli, deflate), custom headers, file sending utilities, and wildcard route handling.

Package Information

  • Package Name: @fastify/static
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install @fastify/static

Core Imports

const fastifyStatic = require('@fastify/static');

For ES modules:

import fastifyStatic from '@fastify/static';

Basic Usage

const fastify = require('fastify')({ logger: true });
const path = require('node:path');

// Register the static plugin
await fastify.register(fastifyStatic, {
  root: path.join(__dirname, 'public'),
  prefix: '/public/', // optional: default '/'
});

// The plugin adds reply decorators for manual file serving
fastify.get('/download', function (req, reply) {
  reply.sendFile('myfile.pdf'); // serving from the configured root
});

fastify.get('/attachment', function (req, reply) {
  reply.download('report.pdf', 'monthly-report.pdf'); // with custom filename
});

await fastify.listen({ port: 3000 });

Architecture

@fastify/static is built around several key components:

  • Plugin Registration: Main plugin function that configures static file serving routes and reply decorators
  • File Serving Engine: Powered by @fastify/send for efficient file streaming with content negotiation
  • Reply Decorators: sendFile and download methods added to FastifyReply for manual file operations
  • Directory Listing: Optional directory browsing functionality with JSON and HTML formats
  • Content Encoding: Support for pre-compressed files (brotli, gzip, deflate) with automatic negotiation
  • Route Management: Wildcard or pre-scanned route generation with customizable constraints and prefixes

Capabilities

Plugin Registration

Core plugin registration with comprehensive configuration options for static file serving, routing, caching, and content delivery.

/**
 * Main static file serving plugin for Fastify
 * @param fastify - Fastify instance
 * @param options - Plugin configuration options
 */
function fastifyStatic(fastify, options);

interface FastifyStaticOptions extends SendOptions {
  root: string | string[] | URL | URL[];
  prefix?: string;
  prefixAvoidTrailingSlash?: boolean;
  serve?: boolean;
  decorateReply?: boolean;
  schemaHide?: boolean;
  setHeaders?: (res: SetHeadersResponse, path: string, stat: Stats) => void;
  redirect?: boolean;
  wildcard?: boolean;
  globIgnore?: string[];
  allowedPath?: (pathName: string, root: string, request: FastifyRequest) => boolean;
  preCompressed?: boolean;
  list?: boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat;
  constraints?: RouteOptions['constraints'];
  logLevel?: RouteOptions['logLevel'];
}

Plugin Registration

Reply Decorators

Manual file serving methods added to FastifyReply for programmatic file operations with custom headers and download behavior.

interface FastifyReply {
  sendFile(filename: string, rootPath?: string): FastifyReply;
  sendFile(filename: string, options?: SendOptions): FastifyReply;
  sendFile(filename: string, rootPath?: string, options?: SendOptions): FastifyReply;
  download(filepath: string, options?: SendOptions): FastifyReply;
  download(filepath: string, filename?: string): FastifyReply;
  download(filepath: string, filename?: string, options?: SendOptions): FastifyReply;
}

interface SendOptions {
  acceptRanges?: boolean;
  contentType?: boolean;
  cacheControl?: boolean;
  dotfiles?: 'allow' | 'deny' | 'ignore';
  etag?: boolean;
  extensions?: string[];
  immutable?: boolean;
  index?: string[] | string | false;
  lastModified?: boolean;
  maxAge?: string | number;
}

Reply Decorators

Directory Listing

Optional directory browsing functionality that provides JSON and HTML formatted directory contents with extensible rendering and filtering options.

interface ListOptionsJsonFormat {
  format: 'json';
  names?: string[];
  extendedFolderInfo?: boolean;
  jsonFormat?: 'names' | 'extended';
  render?: ListRender;
}

interface ListOptionsHtmlFormat {
  format: 'html';
  render: ListRender;
  names?: string[];
  extendedFolderInfo?: boolean;
}

interface ListRender {
  (dirs: ListDir[], files: ListFile[]): string;
}

Directory Listing

Types

Core Types

// Required imports for types
import { FastifyPluginAsync, FastifyReply, FastifyRequest, RouteOptions } from 'fastify';
import { Stats } from 'node:fs';
interface SetHeadersResponse {
  getHeader: FastifyReply['getHeader'];
  setHeader: FastifyReply['header'];
  readonly filename: string;
  statusCode: number;
}

interface ExtendedInformation {
  fileCount: number;
  totalFileCount: number;
  folderCount: number;
  totalFolderCount: number;
  totalSize: number;
  lastModified: number;
}

interface ListDir {
  href: string;
  name: string;
  stats: Stats;
  extendedInfo?: ExtendedInformation;
}

interface ListFile {
  href: string;
  name: string;
  stats: Stats;
}