@fastify/static
Static file serving plugin for Fastify — serve assets from a local directory with range requests, ETag caching, and index files.
@fastify/static
FastifyStatic file serving plugin for Fastify — serve assets from a local directory with range requests, ETag caching, and index files.
Fit
Bundle (gzip)
49.6 kB
159.0 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Serving static files (images, CSS, JS bundles, built frontend assets) from a Fastify backend requires efficient range request handling, proper caching headers, and index.html fallback for SPA routing.
What It Does
@fastify/static serves files from a directory with automatic ETag generation, Last-Modified headers, and Cache-Control support. It handles partial content (Range) requests for media streaming and can serve multiple directories with different prefixes.
Installation
npm install @fastify/staticUsage Example
import fastify from 'fastify';
import staticFiles from '@fastify/static';
import { join } from 'path';
const app = fastify();
// Serve frontend build
await app.register(staticFiles, {
root: join(__dirname, '../client/dist'),
prefix: '/',
index: 'index.html',
});
// SPA fallback
app.setNotFoundHandler((req, reply) => {
reply.sendFile('index.html');
});Related packages
Auto-load Fastify plugins from a directory — organize routes and plugins as files and let the framework discover them automatically.
@fastify/cookieFastifyPlugin for Fastify that adds support for reading and setting cookies, including signed cookies.
@fastify/corsFastifyCORS plugin for Fastify — configure cross-origin resource sharing with full support for preflight requests and dynamic origins.
@fastify/helmetFastifySecurity headers plugin for Fastify — sets HTTP headers that protect against common web vulnerabilities like XSS, clickjacking, and MIME sniffing.
@fastify/jwtFastifyJWT authentication plugin for Fastify — sign, verify, and decode tokens with a decorator-based API that integrates with Fastify's request lifecycle.