@prexjs/serve-static
v1.0.0
Published
Static file serving middleware for Node.js, Express, and Prex with redirect, index, and header controls.
Readme
@prexjs/serve-static
Static file serving middleware for Node.js, Express, and Prex with redirect, index, and header controls.
@prexjs/serve-static is a Connect/Express-compatible middleware for serving static assets from a root directory. Powered internally by @prexjs/send, it handles automatic directory redirects, custom headers, caching headers, and non-blocking fallthrough.
Features
- Connect & Prex Compatible: Drop-in middleware for Prex, Express, or standard
http.createServerstacks. - Directory Trailing-Slash Redirects: Automatically issues HTTP 301 redirects with proper URL escaping for directory paths without trailing slashes.
- Fallthrough Support: Seamlessly passes control to subsequent route handlers or error middleware when files are not found.
- Custom Header Hooks:
setHeaders(res, path, stat)callback to inject headers based on file type or metadata. - High Performance: Powered by stream pipelines with native RFC caching and byte-range support.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/serve-static
# pnpm
pnpm add @prexjs/serve-static
# Yarn
yarn add @prexjs/serve-static
# Bun
bun add @prexjs/serve-staticQuick start
import http from 'node:http';
import serveStatic from '@prexjs/serve-static';
// Serve files from the "public" directory
const serve = serveStatic('public', {
index: ['index.html'],
maxAge: '1d',
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.setHeader('Cache-Control', 'public, max-age=0');
}
},
});
const server = http.createServer((req, res) => {
serve(req, res, (err) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');
return;
}
// Fallthrough: route was not matched by a static file
res.statusCode = 404;
res.end('Not Found');
});
});
server.listen(3000);API
serveStatic(root, [options])
Returns a standard Connect-style middleware (req, res, next) => void.
root: Root directory string from which files will be served.options:fallthrough: Whentrue, errors or missing files pass through vianext()rather than ending response with 404 (default:true).redirect: Redirect to trailing slash when pathname is a directory (default:true).setHeaders: Callback function(res, path, stat) => voidfor adding headers.dotfiles: How to treat dotfiles ('allow','deny','ignore').etag: Enable/disable etag generation.extensions: File extension fallbacks (e.g.,['html', 'htm']).index: Index file name (default:'index.html').maxAge: Max-age in milliseconds or string format (default:0).
Compatibility
- Node.js >= 18.0.0
- Supports both ESM and CommonJS
- TypeScript 5.0+
Related Packages
@prexjs/send: Low-level static streaming library.@prexjs/parseurl: Fast URL parser with memoization.@prexjs/encodeurl: URL encoder.
