Zap is a lightweight HTTP server framework for Node.
Install with your favorite package manager:
$ pnpm add zap
$ yarn add zap
$ npm install zapimport {route, router, serve} from 'zap'
const app = router(
route('GET', '/', () => 'Hello World'),
route('GET', '/hello/:name', (req) => `Hello ${req.params.name}`),
)
const server = http.createServer(serve(app))
server.listen(3000)Constructs a new http.RequestListener out of a Handler.
Constructs a new Handler out of a list of RouteHandlers.
Constructs a RouteHandler that matches a given method (GET, POST, etc) and path.
buffer(req, options)- read the request body as aBuffertext(req, options)- read the request body as a stringjson(req, options)- read the request body as parsed JSON
getHeader(req, header)- returns the requested header if it was providedfromRequest(fn)- wraps a function in the form(req: ServerRequest, ...rest) => anyto return an equivalent function that caches its results for the provided request
- Ordinarily you would return a
ResponseBodyTypefrom aHandlerfunction send(res, statusCode, body)- a response with a given status codenotFound()- a 404 responseredirect(location, statusCode)- a redirect to another location (default status code 303)httpError(code, message, metadata)- an error response with a given code, message, and optional metadata
You can use a function that throws an httpError to provide type-safe body payload parsing:
async function parseBody(req: ServerRequest) {
const body = await json(req)
if (!validate(body)) throw httpError(400, 'invalid body')
return body
}
route('POST', '/example', (req) => {
const body = await parseBody(req)
// body is now typed according to your parseBody return type
})The serve() function options accept an errorHandler that will replace zap's built-in error handler. This allows you to report errors to services like Sentry, format the response sent to the user, etc.
serve(handler, {
errorHandler: (_, res, error) => {
send(res, 500, {message: 'Internal server error', details: formatError(error)})
},
})Special thanks to @nornagon for the zap package name. For versions of this module published before v1.0.0, see nornagon/node-zap.
MIT License, see LICENSE.