Security News
Highlights from the 2024 Rails Community Survey
A record 2,709 developers participated in the 2024 Ruby on Rails Community Survey, revealing key tools, practices, and trends shaping the Rails ecosystem.
The sirv npm package is a simple, high-performance, single-purpose HTTP server for serving static files. It is designed to be fast and efficient, making it ideal for serving the static assets of web applications.
Serving static files
This code sample demonstrates how to use sirv with Polka (a lightweight web server) to serve static files from the 'public' directory.
const sirv = require('sirv');
const polka = require('polka');
const server = polka();
server.use(sirv('public'));
server.listen(3000, err => {
if (err) throw err;
console.log('> Running on localhost:3000');
});
Customizing options
This code sample shows how to customize sirv with options such as cache control headers and enabling single-page application (SPA) mode.
const sirv = require('sirv');
const options = {
maxAge: 31536000, // 1 year in seconds
immutable: true,
etag: true,
single: true
};
const serve = sirv('public', options);
Using with middleware
This code sample illustrates how to use sirv as middleware in an Express application to serve static files with development options enabled.
const sirv = require('sirv');
const express = require('express');
const app = express();
app.use(sirv('public', { dev: true }));
app.listen(3000, () => console.log('Server running on port 3000'));
Express' built-in middleware function to serve static files. It is part of the Express.js framework and is widely used for serving static assets. Compared to sirv, it is more feature-rich but also heavier due to being part of a larger framework.
A Node.js middleware for serving static files that is compatible with many frameworks like Express. It is similar to sirv but offers more configuration options and is part of the larger Express ecosystem.
A static file serving middleware for Koa, which is another web framework for Node.js. Koa-static is designed to work within the Koa ecosystem and provides a similar feature set to sirv but is tailored for Koa's middleware pattern.
The optimized and lightweight middleware for serving requests to static assets
You may use sirv
as a very fast and lightweight alternative to serve-static
. While (currently), sirv
may not have the same options, it handles the majority of use cases without a hitch!
The massive performance advantage over serve-static
is explained by not relying on the file system for existence checks on every request. These are expensive interactions & must be avoided whenever possible! Instead, sirv
performs all its work upfront and recycles the initial resultset for existence checks & writing header values based on files' stats.
This middleware will work out of the box for Polka and other Express-like frameworks. It requires very little effort to modify/wrap it for servers that don't accept the (req, res, next)
signature.
:bulb: For a feature-complete CLI application, check out the sibling sirv-cli
package as an alternative to zeit/serve
~!
$ npm install --save sirv
const sirv = require('sirv');
const polka = require('polka');
const compress = require('compression')();
// Init `sirv` handler
const assets = sirv('public', {
maxAge: 31536000, // 1Y
immutable: true
});
polka()
.use(compress, assets)
.use('/api', require('./api'))
.listen(3000)
.then(() => {
console.log('> Ready on localhost:3000~!');
});
Returns: Function
The returned function is a middleware in the standard Express-like signature: (req, res, next)
, where req
is the http.IncomingMessage
, res
is the http.ServerResponse
, and next
(in this case) is the function to call if no file was found for the given path.
For sirv
, the next()
callback is functionally synonymous with opts.onNoMatch
; however next()
is given priority if/when defined and will not receive the res
as an argument.
Type: String
Default: .
The directory from which to read and serve assets. It is resolved to an absolute path — you must provide an absolute path yourself if process.cwd()
is not the correct assumption.
Type: Boolean
Default: false
Generate and attach an ETag
header to responses.
Type: Boolean
Default: false
Allow requests to dotfiles (files or directories beginning with a .
).
Type: Array
Default: ['html', 'htm']
The file extension fallbacks to check for if a pathame is not initially found. For example, if a /login
request cannot find a login
filename, it will then look for login.html
and login.htm
before giving up~!
Important: Actually,
sirv
will also look forlogin/index.html
andlogin/index.htm
before calling it quits.
Type: Number
Default: undefined
Enables the Cache-Control
header on responses & sets the max-age
value (in seconds). For example 31536000
is equivalent to one year.
Type: Boolean
Default: false
Appends the immutable
directive on your Cache-Control
header, used for uniquely-named assets that will not change!
Note: Requires
opts.maxAge
to contain a value!
Type: Function
A custom function to run if a file cannot be found for a given request.
By default, sirv
will send a basic (404) Not found
response.
The function receives the current res <ServerResponse>
as its only argument.
Note: This won't run if a
next
callback has been provided to the middleware; seesirv
description.
Type: Function
A custom function to append or change any headers on the outgoing response. There is no default.
Its signature is (res, pathname, stats)
, where res
is the ServerResponse
, pathname
is incoming request path (stripped of queries), and stats
is the file's result from fs.statSync
.
MIT © Luke Edwards
FAQs
The optimized & lightweight middleware for serving requests to static assets
The npm package sirv receives a total of 6,977,732 weekly downloads. As such, sirv popularity was classified as popular.
We found that sirv demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A record 2,709 developers participated in the 2024 Ruby on Rails Community Survey, revealing key tools, practices, and trends shaping the Rails ecosystem.
Security News
In 2023, data breaches surged 78% from zero-day and supply chain attacks, but developers are still buried under alerts that are unable to prevent these threats.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.