• Stars
    star
    564
  • Rank 79,014 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The foundation of `serve`

serve-handler

Tests codecov install size

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.

Usage

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! ๐ŸŽ‰

Options

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

public (String)

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.

cleanUrls (Boolean|Array)

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.

rewrites (Array)

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).

redirects (Array)

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).

headers (Array)

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.

directoryListing (Boolean|Array)

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.

unlisted (Array)

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.

trailingSlash (Boolean)

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/.

renderSingle (Boolean)

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.

symlinks (Boolean)

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.

etag (Boolean)

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
}

Error templates

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.

Middleware

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.

Author

Leo Lamprecht (@notquiteleo) - Vercel

More Repositories

1

next.js

The React Framework
JavaScript
126,710
star
2

hyper

A terminal built on web technologies
TypeScript
43,324
star
3

swr

React Hooks for Data Fetching
TypeScript
30,461
star
4

turborepo

Build system optimized for JavaScriptย and TypeScript, written in Rust
Rust
25,810
star
5

pkg

Package your Node.js project into an executable
JavaScript
24,260
star
6

vercel

Develop. Preview. Ship.
TypeScript
12,555
star
7

commerce

Next.js Commerce
TypeScript
11,287
star
8

satori

Enlightened library to convert HTML and CSS to SVG
TypeScript
11,019
star
9

micro

Asynchronous HTTP microservices
TypeScript
10,525
star
10

ai

Build AI-powered applications with React, Svelte, Vue, and Solid
TypeScript
9,836
star
11

serve

Static file serving and directory listing
TypeScript
9,208
star
12

ncc

Compile a Node.js project into a single file. Supports TypeScript, binary addons, dynamic requires.
JavaScript
9,063
star
13

styled-jsx

Full CSS support for JSX without compromises
JavaScript
7,677
star
14

ai-chatbot

A full-featured, hackable Next.js AI chatbot built by Vercel
TypeScript
6,579
star
15

nextjs-subscription-payments

Clone, deploy, and fully customize a SaaS subscription application with Next.js.
TypeScript
6,499
star
16

platforms

A full-stack Next.js app with multi-tenancy and custom domain support. Built with Next.js App Router and the Vercel Domains API.
TypeScript
5,650
star
17

ms

Tiny millisecond conversion utility
TypeScript
4,912
star
18

og-image

Open Graph Image as a Service - generate cards for Twitter, Facebook, Slack, etc
TypeScript
4,051
star
19

next-learn

Learn Next.js Starter Code
TypeScript
3,710
star
20

release

Generate changelogs with a single command
JavaScript
3,558
star
21

examples

Enjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.
TypeScript
3,556
star
22

hazel

Lightweight update server for Electron apps
JavaScript
2,896
star
23

next-plugins

Official Next.js plugins
2,677
star
24

next-app-router-playground

https://app-router.vercel.app/
TypeScript
2,534
star
25

geist-font

2,250
star
26

virtual-event-starter-kit

Open source demo that Next.js developers can clone, deploy, and fully customize for events.
TypeScript
2,148
star
27

async-retry

Retrying made simple, easy and async
JavaScript
1,808
star
28

react-tweet

Embed tweets in your React application.
TypeScript
1,615
star
29

little-date

A friendly formatter to make date ranges small & sweet
TypeScript
1,553
star
30

nft

Node.js dependency tracing utility
JavaScript
1,287
star
31

arg

Simple argument parsing
JavaScript
1,222
star
32

style-guide

Vercel's engineering style guide
JavaScript
1,209
star
33

avatar

๐Ÿ’Ž Beautiful avatars as a microservice
TypeScript
1,155
star
34

nextjs-postgres-nextauth-tailwindcss-template

Admin dashboard template.
TypeScript
1,108
star
35

modelfusion

The TypeScript library for building AI applications.
TypeScript
1,084
star
36

next-react-server-components

Demo repository for Next.js + React Server Components
JavaScript
985
star
37

nextjs-postgres-auth-starter

Next.js + Tailwind + Typescript + Drizzle + NextAuth + PostgreSQL starter template.
TypeScript
915
star
38

nextgram

A sample Next.js app showing dynamic routing with modals as a route.
TypeScript
867
star
39

edge-runtime

Developing, testing, and defining the runtime Web APIs for Edge infrastructure.
TypeScript
790
star
40

on-demand-isr

TypeScript
762
star
41

server-components-notes-demo

Experimental demo of React Server Components with Next.js. Deployed serverlessly on Vercel.
TypeScript
734
star
42

micro-dev

The development environment for `micro`
JavaScript
705
star
43

nextjs-portfolio-starter

Easily create a portfolio with Next.js and Markdown.
JavaScript
669
star
44

async-sema

Semaphore using `async` and `await`
TypeScript
631
star
45

static-fun

A fun demo for wildcard domains
TypeScript
629
star
46

hyperpower

Hyper particle effects extension
JavaScript
623
star
47

react-keyframes

Create frame-based animations in React
TypeScript
617
star
48

title

A service for capitalizing your title properly
JavaScript
579
star
49

fetch

Opinionated `fetch` (with retrying and DNS caching) optimized for use with Node.js
JavaScript
568
star
50

vrs

A serverless virtual reality e-commerce experience powered by Vercel
TypeScript
517
star
51

storage

Vercel Postgres, KV, Blob, and Edge Config
TypeScript
506
star
52

fun

ฦ’un - Local serverless function ฮป development runtime
TypeScript
480
star
53

swr-site

The official website for SWR.
MDX
479
star
54

mongodb-starter

A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integration.
TypeScript
470
star
55

hyper-site

The official website for the Hyper terminal
JavaScript
435
star
56

spr-landing

Serverless Pre-Rendering Landing Page
CSS
434
star
57

pkg-fetch

A utility to fetch or build patched Node binaries used by `pkg` to generate executables. This repo hosts prebuilt binaries in Releases.
TypeScript
428
star
58

analytics

Privacy-friendly, real-time traffic insights
TypeScript
421
star
59

sveltekit-commerce

SvelteKit Commerce
Svelte
386
star
60

reactions

Next.js Incremental Static Regeneration Demo
JavaScript
309
star
61

email-prompt

CLI email prompt with autocompletion and built-in validation
JavaScript
274
star
62

uid-promise

Creates a cryptographically strong UID
TypeScript
252
star
63

fetch-retry

Wrapper around `fetch` with sensible retrying defaults
JavaScript
221
star
64

git-hooks

No nonsense Git hook management
JavaScript
202
star
65

zsh-theme

Yet another zsh theme
179
star
66

remote-cache

The Vercel Remote Cache SDK
TypeScript
174
star
67

cosmosdb-server

A Cosmos DB server implementation for testing your applications locally.
TypeScript
170
star
68

react-transition-progress

Show a progress bar while React Transitions run
TypeScript
162
star
69

update-check

Minimalistic update notifications for command line interfaces
JavaScript
159
star
70

test-listen

Quick ephemeral URLs for your tests
JavaScript
153
star
71

terraform-provider-vercel

Terraform Vercel Provider
Go
142
star
72

install-node

Simple one-liner shell script that installs official Node.js binaries
Shell
141
star
73

title-site

A website for capitalizing your titles
JavaScript
126
star
74

community

Welcome to the Vercel Community. Discuss feature requests, ask questions, and connect with others in the community.
111
star
75

preview-mode-demo

This demo showcases Next.js' next-gen Static Site Generation (SSG) support.
TypeScript
110
star
76

nextjs-discord-bot

Discord bot for the official Next.js Discord
TypeScript
108
star
77

beginner-sveltekit

The complete course to start your journey building Svelte applications.
JavaScript
101
star
78

commerce-framework

TypeScript
99
star
79

err-sh

Microservice that forwards you to error messages
JavaScript
97
star
80

webpack-asset-relocator-loader

Used in ncc while emitting and relocating any asset references
JavaScript
96
star
81

hyperyellow

Example theme for hyperterm
JavaScript
87
star
82

schemas

All schemas used for validation that are shared between our projects
JavaScript
80
star
83

opentelemetry-collector-dev-setup

Shell
72
star
84

nuxt3-kitchen-sink

An example template showing all Nuxt 3 features on Vercel.
Vue
67
star
85

next-codemod

codemod transformations to help upgrade Next.js codebases
JavaScript
63
star
86

speed-insights

Vercel Speed Insights package
TypeScript
56
star
87

ai-sdk-rag-starter

TypeScript
55
star
88

wait-for

Small utility that waits for a file to exist and optionally have some permissions set.
C
46
star
89

async-listen

Promisify server.listen for your HTTP/HTTPS/TCP server.
TypeScript
45
star
90

tracing-js

An implementation of Opentracing API for honeycomb.io
TypeScript
43
star
91

example-integration

TypeScript
42
star
92

dns-cached-resolve

Caching DNS resolver
TypeScript
41
star
93

fetch-cached-dns

A decorator on top of `fetch` that caches the DNS query
JavaScript
36
star
94

resolve-node

API endpoint to resolve an arbitrary Node.js version with semver support
JavaScript
30
star
95

remark-capitalize

Transform all markdown titles with title.sh
JavaScript
29
star
96

cra-to-next

An example of migrating Create React App to Next.js.
JavaScript
29
star
97

otel

OTEL tracing for Vercel
TypeScript
27
star
98

stripe-integration

A Vercel deploy integration to automatically set up your Stripe API keys and webhook secrets.
TypeScript
25
star
99

rcurl

`curl --resolve` helper script
Shell
23
star
100

gatsby-plugin-vercel

Track Core Web Vitals in Gatsby projects with Vercel Analytics.
JavaScript
21
star