![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
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. 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 using 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:
Property | Description |
---|---|
public | Set a sub directory to be served |
cleanUrls | Have the .html extension stripped from paths |
rewrites | Rewrite paths to different paths |
redirects | Forward paths to different paths or external URLs |
headers | Set custom headers for specific paths |
directoryListing | Disable directory listing or restrict it to certain paths |
unlisted | Exclude paths from the directory listing |
trailingSlash | Remove or add trailing slashes to all paths |
renderSingle | If a directory only contains one file, render it |
symlinks | Resolve symlinks instead of rendering a 404 error |
etag | Calculate a strong ETag response header, instead of Last-Modified |
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 an absolute path or 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"
}
Using absolute path:
{
"public": "/path/to/your/_site"
}
NOTE: The path cannot contain globs or regular expressions.
By default, all .html
files can be accessed without their extension.
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.
You can disable the feature like follows:
{
"cleanUrls": false
}
However, you can also restrict it to certain paths:
{
"cleanUrls": [
"/app/**",
"/!components/**"
]
}
NOTE: The paths can only contain globs that are matched using minimatch.
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
.
NOTE: The paths can contain globs (matched using minimatch) or regular expressions (match using path-to-regexp).
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.
NOTE: The paths can contain globs (matched using minimatch) or regular expressions (match using path-to-regexp).
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"
}]
}
]
}
If you define the ETag
header for a path, the handler will automatically reply with status code 304
for that path if a request comes in with a matching If-None-Match
header.
If you set a header value
to null
it removes any previous defined header with the same key.
NOTE: The paths can only contain globs that are matched using minimatch.
For paths are not files, but directories, the package will automatically render a good-looking list of all the files and directories contained inside that directory.
If you'd like to disable this for all paths, set this option to false
. Furthermore, you can also restrict it to certain directory paths if you want:
{
"directoryListing": [
"/assets/**",
"/!assets/private"
]
}
NOTE: The paths can only contain globs that are matched using minimatch.
In certain cases, you might not want a file or directory to appear in the directory listing. In these situations, there are two ways of solving this problem.
Either you disable the directory listing entirely (like shown here), or you exclude certain paths from those listings by adding them all to this config property.
{
"unlisted": [
".DS_Store",
".git"
]
}
The items shown above are excluded from the directory listing by default.
NOTE: The paths can only contain globs that are matched using minimatch.
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/
.
Sometimes you might want to have a directory path actually render a file, if the directory only contains one. This is only useful for any files that are not .html
files (for those, cleanUrls
is faster).
This is disabled by default and can be enabled like this:
{
"renderSingle": true
}
After that, if you access your directory /test
(for example), you will see an image being rendered if the directory contains a single image file.
For security purposes, symlinks are disabled by default. If serve-handler
encounters a symlink, it will treat it as if it doesn't exist in the first place. In turn, a 404 error is rendered for that path.
However, this behavior can easily be adjusted:
{
"symlinks": true
}
Once this property is set as shown above, all symlinks will automatically be resolved to their targets.
HTTP response headers will contain a strong ETag
response header, instead of a Last-Modified
header. Opt-in because calculating the hash value may be computationally expensive for large files.
Sending an ETag
header is disabled by default and can be enabled like this:
{
"etag": true
}
The handler will automatically determine the right error format if one occurs and then sends it to the client in that format.
Furthermore, this allows you to not just specifiy an error template for 404
errors, but also for all other errors that can occur (e.g. 400
or 500
).
Just add a <status-code>.html
file to the root directory and you're good.
If you want to replace the methods the package is using for interacting with the file system and sending responses, you can pass them as the fourth argument to the function call.
These are the methods used by the package (they can all return a Promise
or be asynchronous):
await handler(request, response, undefined, {
lstat(path) {},
realpath(path) {},
createReadStream(path, config) {}
readdir(path) {},
sendError(absolutePath, response, acceptsJSON, root, handlers, config, error) {}
});
NOTE: It's important that – for native methods like createReadStream
– all arguments are passed on to the native call.
FAQs
The routing foundation of `serve`
The npm package serve-handler receives a total of 1,856,153 weekly downloads. As such, serve-handler popularity was classified as popular.
We found that serve-handler demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 8 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
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.