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.
serve-handler
Advanced tools
The serve-handler package is designed to be used with a Node.js server to serve static files, single-page applications, and directory listings. It provides a simple way to configure how files are served, with options for rewrites, redirects, headers, and more.
Serving static files
This code creates a simple server that serves static files from the current directory on port 3000 using the default configuration.
const serveHandler = require('serve-handler');
const http = require('http');
http.createServer((request, response) => {
return serveHandler(request, response);
}).listen(3000);
Custom routing with rewrites
This code demonstrates how to use the rewrites option to redirect requests from 'some/path/*' to '/index.html', which is useful for single-page applications.
const serveHandler = require('serve-handler');
const http = require('http');
http.createServer((request, response) => {
return serveHandler(request, response, {
rewrites: [{ source: 'some/path/*', destination: '/index.html' }]
});
}).listen(3000);
Custom headers
This code shows how to set custom headers for all files served. In this example, all responses will include the 'X-Custom-Header' with the value 'Custom Value'.
const serveHandler = require('serve-handler');
const http = require('http');
http.createServer((request, response) => {
return serveHandler(request, response, {
headers: [{ source: '**/*', headers: [{ key: 'X-Custom-Header', value: 'Custom Value' }] }]
});
}).listen(3000);
Directory listings
This code enables directory listings, allowing users to view the contents of directories that do not contain an index file.
const serveHandler = require('serve-handler');
const http = require('http');
http.createServer((request, response) => {
return serveHandler(request, response, {
directoryListing: true
});
}).listen(3000);
Express is a popular web application framework for Node.js. It can serve static files and be extended with middleware for more complex routing and server-side logic. It is more feature-rich than serve-handler but also more complex.
http-server is a simple, zero-configuration command-line HTTP server. It is globally installed and can serve static files. It is similar to serve-handler but does not provide as much configuration flexibility.
serve-static is middleware for serving static files for Express. It is similar to serve-handler but is specifically designed to be used with the Express framework.
koa-static is a static file serving middleware for Koa, another Node.js web framework. It is similar to serve-handler but is tailored for use with Koa.
This package represents the core of serve and static deployments running on Now. It can be plugged into any HTTP server and is responsible for routing requests and handling responses.
In order to customize the default behaviour, you can also pass custom routing rules, provide your own methods for interacting with the file system and much more.
Get started by installing the package using yarn:
yarn add serve-handler
You can also use npm instead, if you'd like:
npm install serve-handler
Next, add it to your HTTP server. Here's an example with micro:
const handler = require('serve-handler');
module.exports = async (request, response) => {
await handler(request, response);
};
That's it! :tada:
If you want to customize the package's default behaviour, you can use the third argument of the function call to pass any of the configuration options listed below. Here's an example:
await handler(request, response, {
cleanUrls: true
});
You can use any of the following options:
.html
and .htm
from paths)By default, the current working directory will be served. If you only want to serve a specific path, you can use this options to pass a custom directory to be served relative to the current working directory.
For example, if serving a Jekyll app, it would look like this:
{
"public": "_site"
}
Assuming this is true
, all .html
and .htm
files can be accessed without their extension (shown below).
If one of these extensions is used at the end of a filename, it will automatically perform a redirect with status code 301 to the same path, but with the extension dropped.
{
"cleanUrls": true
}
However, you can also restrict this behavior to certain paths:
{
"cleanUrls": [
"/app/**",
"/!components/**"
]
}
If you want your visitors to receive a response under a certain path, but actually serve a completely different one behind the curtains, this option is what you need.
It's perfect for single page applications (SPAs), for example:
{
"rewrites": [
{ "source": "app/**", "destination": "/index.html" },
{ "source": "projects/*/edit", "destination": "/edit-project.html" }
]
}
You can also use so-called "routing segments" as follows:
{
"rewrites": [
{ "source": "/projects/:id/edit", "destination": "/edit-project-:id.html" },
]
}
Now, if a visitor accesses /projects/123/edit
, it will respond with the file /edit-project-123.html
.
In order to redirect visits to a certain path to a different one (or even an external URL), you can use this option:
{
"redirects": [
{ "source": "/from", "destination": "/to" },
{ "source": "/old-pages/**", "destination": "/home" }
]
}
By default, all of them are performed with the status code 301, but this behavior can be adjusted by setting the type
property directly on the object (see below).
Just like with rewrites, you can also use routing segments:
{
"redirects": [
{ "source": "/old-docs/:id", "destination": "/new-docs/:id" },
{ "source": "/old", "destination": "/new", "type": 302 }
]
}
In the example above, /old-docs/12
would be forwarded to /new-docs/12
with status code 301. In addition /old
would be forwarded to /new
with status code 302.
Allows you to set custom headers (and overwrite the default ones) for certain paths:
{
"headers": [
{
"source" : "**/*.@(jpg|jpeg|gif|png)",
"headers" : [{
"key" : "Cache-Control",
"value" : "max-age=7200"
}]
}, {
"source" : "404.html",
"headers" : [{
"key" : "Cache-Control",
"value" : "max-age=300"
}]
}]
}
}
By default, the package will try to make assumptions for when to add trailing slashes to your URLs or not. If you want to remove them, set this property to false
and true
if you want to force them on all URLs:
{
"trailingSlash": true
}
With the above config, a request to /test
would now result in a 301 redirect to /test/
.
If you want to replace the methods the package is using for interacting with the file system, you can pass them as the fourth argument to the function call.
This comes in handy if you're dealing with simulating a file system, for example.
These are the methods used by the package (they can all return a Promise
or be asynchronous):
await handler(request, response, null, {
createReadStream(path) {},
stat(path) {}
});
There are two environments in which ZEIT uses this package:
When running static applications or sites on your local device, we suggest using serve.
Since it comes with support for serve-handler
out of the box, you can create a serve.json
file to customize its behavior. It will also read the configuration from static
inside now.json
.
When deploying your site to Now, both the serve.json
file or the static
property inside now.json
will be parsed and used to handle requests on the platform.
Leo Lamprecht (@notquiteleo) - ZEIT
FAQs
The routing foundation of `serve` and static deployments on Now
The npm package serve-handler receives a total of 1,359,048 weekly downloads. As such, serve-handler popularity was classified as popular.
We found that serve-handler demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 7 open source maintainers 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.