@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.
npm install @fastify/staticconst fastifyStatic = require('@fastify/static');For ES modules:
import fastifyStatic from '@fastify/static';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 });@fastify/static is built around several key components:
sendFile and download methods added to FastifyReply for manual file operationsCore 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'];
}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;
}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;
}// 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;
}