{"id":13426240,"url":"https://github.com/jeremydaly/lambda-api","last_synced_at":"2025-04-12T11:45:45.191Z","repository":{"id":26100785,"uuid":"106726943","full_name":"jeremydaly/lambda-api","owner":"jeremydaly","description":"Lightweight web framework for your serverless applications","archived":false,"fork":false,"pushed_at":"2024-09-28T16:32:03.000Z","size":988,"stargazers_count":1426,"open_issues_count":41,"forks_count":126,"subscribers_count":38,"default_branch":"main","last_synced_at":"2024-10-29T15:29:06.120Z","etag":null,"topics":["api","api-gateway","aws-lambda","nodejs","serverless","serverless-applications","webframework"],"latest_commit_sha":null,"homepage":"https://serverless-api.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jeremydaly.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-12T17:54:22.000Z","updated_at":"2024-10-28T09:12:26.000Z","dependencies_parsed_at":"2023-11-26T06:29:56.692Z","dependency_job_id":"537e1953-88f5-413b-841c-016a6caad1a4","html_url":"https://github.com/jeremydaly/lambda-api","commit_stats":{"total_commits":411,"total_committers":37,"mean_commits":"11.108108108108109","dds":0.2798053527980535,"last_synced_commit":"5edcd8a6f793dee5a29f6389182e0ce3e417665b"},"previous_names":[],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremydaly%2Flambda-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremydaly%2Flambda-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremydaly%2Flambda-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremydaly%2Flambda-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jeremydaly","download_url":"https://codeload.github.com/jeremydaly/lambda-api/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248564566,"owners_count":21125408,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-gateway","aws-lambda","nodejs","serverless","serverless-applications","webframework"],"created_at":"2024-07-31T00:01:29.789Z","updated_at":"2025-04-12T11:45:45.175Z","avatar_url":"https://github.com/jeremydaly.png","language":"JavaScript","readme":"[![Lambda API](https://www.jeremydaly.com/images/uploads/2018/03/lambda-api-logo.png)](https://serverless-api.com/)\n\n[![Build Status](https://github.com/jeremydaly/lambda-api/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/jeremydaly/lambda-api/actions/workflows/build.yml)\n[![npm](https://img.shields.io/npm/v/lambda-api.svg)](https://www.npmjs.com/package/lambda-api)\n[![npm](https://img.shields.io/npm/l/lambda-api.svg)](https://www.npmjs.com/package/lambda-api)\n[![Coverage Status](https://coveralls.io/repos/github/jeremydaly/lambda-api/badge.svg?branch=main)](https://coveralls.io/github/jeremydaly/lambda-api?branch=main)\n\n### Lightweight web framework for your serverless applications\n\nLambda API is a lightweight web framework for AWS Lambda using AWS API Gateway Lambda Proxy Integration or ALB Lambda Target Support. This closely mirrors (and is based on) other web frameworks like Express.js and Fastify, but is significantly stripped down to maximize performance with Lambda's stateless, single run executions.\n\n## Using AWS SDK v2?\n\nlambda-api@v1 is using AWS SDK v3.\nIf you are using AWS SDK v2, please use lambda-api@v0.12.0.\n\n## Simple Example\n\n```javascript\n// Require the framework and instantiate it\nconst api = require('lambda-api')();\n\n// Define a route\napi.get('/status', async (req, res) =\u003e {\n  return { status: 'ok' };\n});\n\n// Declare your Lambda handler\nexports.handler = async (event, context) =\u003e {\n  // Run the request\n  return await api.run(event, context);\n};\n```\n\nFor a full tutorial see [How To: Build a Serverless API with Serverless, AWS Lambda and Lambda API](https://www.jeremydaly.com/build-serverless-api-serverless-aws-lambda-lambda-api/).\n\n## Why Another Web Framework?\n\nExpress.js, Fastify, Koa, Restify, and Hapi are just a few of the many amazing web frameworks out there for Node.js. So why build yet another one when there are so many great options already? One word: **DEPENDENCIES**.\n\nThese other frameworks are extremely powerful, but that benefit comes with the steep price of requiring several additional Node.js modules. Not only is this a bit of a security issue (see Beware of Third-Party Packages in [Securing Serverless](https://www.jeremydaly.com/securing-serverless-a-newbies-guide/)), but it also adds bloat to your codebase, filling your `node_modules` directory with a ton of extra files. For serverless applications that need to load quickly, all of these extra dependencies slow down execution and use more memory than necessary. Express.js has **30 dependencies**, Fastify has **12**, and Hapi has **17**! These numbers don't even include their dependencies' dependencies.\n\nLambda API has **ZERO** dependencies. _None_. _Zip_. _Zilch_.\n\nLambda API was written to be _extremely lightweight_ and built specifically for **SERVERLESS** applications using AWS Lambda and API Gateway. It provides support for API routing, serving up HTML pages, issuing redirects, serving binary files and much more. Worried about observability? Lambda API has a built-in logging engine that can even periodically sample requests for things like tracing and benchmarking. It has a powerful middleware and error handling system, allowing you to implement just about anything you can dream of. Best of all, it was designed to work with Lambda's Proxy Integration, automatically handling all the interaction with API Gateway for you. It parses **REQUESTS** and formats **RESPONSES**, allowing you to focus on your application's core functionality, instead of fiddling with inputs and outputs.\n\n### Single Purpose Functions\n\nYou may have heard that a serverless \"best practice\" is to keep your functions small and limit them to a single purpose. I generally agree since building monolith applications is not what serverless was designed for. However, what exactly is a \"single purpose\" when it comes to building serverless APIs and web services? Should we create a separate function for our \"create user\" `POST` endpoint and then another one for our \"update user\" `PUT` endpoint? Should we create yet another function for our \"delete user\" `DELETE` endpoint? You certainly could, but that seems like a lot of repeated boilerplate code. On the other hand, you could create just one function that handled all your user management features. It may even make sense (in certain circumstances) to create one big serverless function handling several related components that can share your VPC database connections.\n\nWhatever you decide is best for your use case, **Lambda API** is there to support you. Whether your function has over a hundred routes, or just one, Lambda API's small size and lightning fast load time has virtually no impact on your function's performance. You can even define global wildcard routes that will process any incoming request, allowing you to use API Gateway or ALB to determine the routing. Yet despite its small footprint, it gives you the power of a full-featured web framework.\n\n## Table of Contents\n\n- [Simple Example](#simple-example)\n- [Why Another Web Framework?](#why-another-web-framework)\n  - [Single Purpose Functions](#single-purpose-functions)\n- [Table of Contents](#table-of-contents)\n- [Installation](#installation)\n- [Requirements](#requirements)\n- [Configuration](#configuration)\n- [Recent Updates](#recent-updates)\n  - [v0.11: API Gateway v2 payload support and automatic compression](#v011-api-gateway-v2-payload-support-and-automatic-compression)\n  - [v0.10: ALB support, method-based middleware, and multi-value headers and query string parameters](#v010-alb-support-method-based-middleware-and-multi-value-headers-and-query-string-parameters)\n- [Routes and HTTP Methods](#routes-and-http-methods)\n- [Returning Responses](#returning-responses)\n  - [Async/Await](#asyncawait)\n  - [Promises](#promises)\n  - [A Note About Flow Control](#a-note-about-flow-control)\n- [Route Prefixing](#route-prefixing)\n- [Debugging Routes](#debugging-routes)\n- [REQUEST](#request)\n- [RESPONSE](#response)\n  - [status(code)](#statuscode)\n  - [sendStatus(code)](#sendstatuscode)\n  - [header(key, value [,append])](#headerkey-value-append)\n  - [getHeader(key [,asArray])](#getheaderkey-asarray)\n  - [getHeaders()](#getheaders)\n  - [hasHeader(key)](#hasheaderkey)\n  - [removeHeader(key)](#removeheaderkey)\n  - [getLink(s3Path [, expires] [, callback])](#getlinks3path--expires--callback)\n  - [send(body)](#sendbody)\n  - [json(body)](#jsonbody)\n  - [jsonp(body)](#jsonpbody)\n  - [html(body)](#htmlbody)\n  - [type(type)](#typetype)\n  - [location(path)](#locationpath)\n  - [redirect([status,] path)](#redirectstatus-path)\n  - [cors([options])](#corsoptions)\n  - [error([code], message [,detail])](#errorcode-message-detail)\n  - [cookie(name, value [,options])](#cookiename-value-options)\n  - [clearCookie(name [,options])](#clearcookiename-options)\n  - [etag([boolean])](#etagboolean)\n  - [cache([age] [, private])](#cacheage--private)\n  - [modified(date)](#modifieddate)\n  - [attachment([filename])](#attachmentfilename)\n  - [download(file [, filename] [, options] [, callback])](#downloadfile--filename--options--callback)\n  - [sendFile(file [, options] [, callback])](#sendfilefile--options--callback)\n- [Enabling Binary Support](#enabling-binary-support)\n- [Path Parameters](#path-parameters)\n- [Wildcard Routes](#wildcard-routes)\n- [Logging](#logging)\n  - [Logging Configuration](#logging-configuration)\n  - [Log Format](#log-format)\n  - [Access Logs](#access-logs)\n  - [Logging Levels](#logging-levels)\n  - [Custom Logging Levels](#custom-logging-levels)\n  - [Adding Additional Detail](#adding-additional-detail)\n  - [Serializers](#serializers)\n  - [Sampling](#sampling)\n- [Middleware](#middleware)\n  - [Restricting middleware execution to certain path(s)](#restricting-middleware-execution-to-certain-paths)\n  - [Specifying multiple middleware](#specifying-multiple-middleware)\n  - [Method-based middleware](#method-based-middleware)\n- [Clean Up](#clean-up)\n- [Error Handling](#error-handling)\n  - [Error Types](#error-types)\n  - [Error Logging](#error-logging)\n- [Namespaces](#namespaces)\n- [CORS Support](#cors-support)\n- [Compression](#compression)\n- [Execution Stacks](#execution-stacks)\n- [Lambda Proxy Integration](#lambda-proxy-integration)\n- [ALB Integration](#alb-integration)\n- [Configuring Routes in API Gateway](#configuring-routes-in-api-gateway)\n- [Reusing Persistent Connections](#reusing-persistent-connections)\n- [TypeScript Support](#typescript-support)\n- [Contributions](#contributions)\n- [Are you using Lambda API?](#are-you-using-lambda-api)\n\n## Installation\n\n```\nnpm i lambda-api --save\n```\n\n## Requirements\n\n- AWS Lambda running **Node 8.10+**\n- AWS API Gateway using [Proxy Integration](#lambda-proxy-integration)\n\n## Configuration\n\nRequire the `lambda-api` module into your Lambda handler script and instantiate it. You can initialize the API with the following options:\n\n| Property             | Type                  | Description                                                                                                                                                                                               |\n| -------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| base                 | `String`              | Base path for all routes, e.g. `base: 'v1'` would prefix all routes with `/v1`                                                                                                                            |\n| callbackName         | `String`              | Override the default callback query parameter name for JSONP calls                                                                                                                                        |\n| logger               | `boolean` or `object` | Enables default [logging](#logging) or allows for configuration through a [Logging Configuration](#logging-configuration) object.                                                                         |\n| mimeTypes            | `Object`              | Name/value pairs of additional MIME types to be supported by the `type()`. The key should be the file extension (without the `.`) and the value should be the expected MIME type, e.g. `application/json` |\n| serializer           | `Function`            | Optional object serializer function. This function receives the `body` of a response and must return a string. Defaults to `JSON.stringify`                                                               |\n| version              | `String`              | Version number accessible via the `REQUEST` object                                                                                                                                                        |\n| errorHeaderWhitelist | `Array`               | Array of headers to maintain on errors                                                                                                                                                                    |\n| s3Config             | `Object`              | Optional object to provide as config to S3 sdk. [S3ClientConfig](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html)                                 |\n\n```javascript\n// Require the framework and instantiate it with optional version and base parameters\nconst api = require('lambda-api')({ version: 'v1.0', base: 'v1' });\n```\n\n## Recent Updates\n\nFor detailed release notes see [Releases](https://github.com/jeremydaly/lambda-api/releases).\n\n### v0.11: API Gateway v2 payload support and automatic compression\n\nLambda API now supports API Gateway v2 payloads for use with HTTP APIs. The library automatically detects the payload, so no extra configuration is needed. Automatic [compression](#compression) has also been added and supports Brotli, Gzip and Deflate.\n\n### v0.10: ALB support, method-based middleware, and multi-value headers and query string parameters\n\nLambda API now allows you to seamlessly switch between API Gateway and Application Load Balancers. New [execution stacks](execution-stacks) enables method-based middleware and more wildcard functionality. Plus full support for multi-value headers and query string parameters.\n\n## Routes and HTTP Methods\n\nRoutes are defined by using convenience methods or the `METHOD` method. There are currently eight convenience route methods: `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()`, `options()` and `any()`. Convenience route methods require an optional _route_ and one or more handler functions. A _route_ is simply a path such as `/users`. If a _route_ is not provided, then it will default to `/*` and will execute on every path. Handler functions accept a `REQUEST`, `RESPONSE`, and optional `next()` argument. These arguments can be named whatever you like, but convention dictates `req`, `res`, and `next`.\n\nMultiple handler functions can be assigned to a path, which can be used to execute middleware for specific paths and methods. For more information, see [Middleware](#middleware) and [Execution Stacks](#execution-stacks).\n\nExamples using convenience route methods:\n\n```javascript\napi.get('/users', (req,res) =\u003e {\n  // do something\n})\n\napi.post('/users', (req,res) =\u003e {\n  // do something\n})\n\napi.delete('/users', (req,res) =\u003e {\n  // do something\n})\n\napi.get('/users',\n  (req,res,next) =\u003e {\n    // do some middleware\n    next() // continue execution\n  }),\n  (req,res) =\u003e {\n    // do something\n  }\n)\n\napi.post((req,res) =\u003e {\n  // do something for ALL post requests\n})\n\n```\n\nAdditional methods are support by calling `METHOD`. Arguments must include an HTTP method (or array of methods), an optional _route_, and one or more handler functions. Like the convenience methods above, handler functions accept a `REQUEST`, `RESPONSE`, and optional `next` argument.\n\n```javascript\napi.METHOD('trace','/users', (req,res) =\u003e {\n  // do something on TRACE\n})\n\napi.METHOD(['post','put'],'/users', (req,res) =\u003e {\n  // do something on POST -or- PUT\n})\n\napi.METHOD('get','/users',\n  (req,res,next) =\u003e {\n    // do some middleware\n    next() // continue execution\n  }),\n  (req,res) =\u003e {\n  // do something\n  }\n)\n```\n\nAll `GET` methods have a `HEAD` alias that executes the `GET` request but returns a blank `body`. `GET` requests should be idempotent with no side effects. The `head()` convenience method can be used to set specific paths for `HEAD` requests or to override default `GET` aliasing.\n\nRoutes that use the `any()` method or pass `ANY` to `api.METHOD` will respond to all HTTP methods. Routes that specify a specific method (such as `GET` or `POST`), will override the route for that method. For example:\n\n```javascript\napi.any('/users', (req, res) =\u003e {\n  res.send('any');\n});\napi.get('/users', (req, res) =\u003e {\n  res.send('get');\n});\n```\n\nA `POST` to `/users` will return \"any\", but a `GET` request would return \"get\". Please note that routes defined with an `ANY` method will override default `HEAD` aliasing for `GET` routes.\n\n## Returning Responses\n\nLambda API supports both `callback-style` and `async-await` for returning responses to users. The [RESPONSE](#response) object has several callbacks that will trigger a response (`send()`, `json()`, `html()`, etc.) You can use any of these callbacks from within route functions and middleware to send the response:\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  res.send({ foo: 'bar' });\n});\n```\n\nYou can also `return` data from route functions and middleware. The contents will be sent as the body:\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  return { foo: 'bar' };\n});\n```\n\n### Async/Await\n\nIf you prefer to use `async/await`, you can easily apply this to your route functions.\n\nUsing `return`:\n\n```javascript\napi.get('/users', async (req, res) =\u003e {\n  let users = await getUsers();\n  return users;\n});\n```\n\nOr using callbacks:\n\n```javascript\napi.get('/users', async (req, res) =\u003e {\n  let users = await getUsers();\n  res.send(users);\n});\n```\n\n### Promises\n\nIf you like promises, you can either use a callback like `res.send()` at the end of your promise chain, or you can simply `return` the resolved promise:\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  getUsers().then((users) =\u003e {\n    res.send(users);\n  });\n});\n```\n\nOR\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  return getUsers().then((users) =\u003e {\n    return users;\n  });\n});\n```\n\n**IMPORTANT:** You must either use a callback like `res.send()` **OR** `return` a value. Otherwise the execution will hang and no data will be sent to the user. Also, be sure not to return `undefined`, otherwise it will assume no response.\n\n### A Note About Flow Control\n\nWhile callbacks like `res.send()` and `res.error()` will trigger a response, they will not necessarily terminate execution of the current route function. Take a look at the following example:\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  if (req.headers.test === 'test') {\n    res.error('Throw an error');\n  }\n\n  return { foo: 'bar' };\n});\n```\n\nThe example above would not have the intended result of displaying an error. `res.error()` would signal Lambda API to execute the error handling, but the function would continue to run. This would cause the function to `return` a response that would override the intended error. In this situation, you could either wrap the return in an `else` clause, or a cleaner approach would be to `return` the call to the `error()` method, like so:\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  if (req.headers.test === 'test') {\n    return res.error('Throw an error');\n  }\n\n  return { foo: 'bar' };\n});\n```\n\n`res.error()` does not have a return value (meaning it is `undefined`). However, the `return` tells the function to stop executing, and the call to `res.error()` handles and formats the appropriate response. This will allow Lambda API to properly return the expected results.\n\n## Route Prefixing\n\nLambda API makes it easy to create multiple versions of the same api without changing routes by hand. The `register()` method allows you to load routes from an external file and prefix all of those routes using the `prefix` option. For example:\n\n```javascript\n// handler.js\nconst api = require('lambda-api')();\n\napi.register(require('./routes/v1/products'), { prefix: '/v1' });\napi.register(require('./routes/v2/products'), { prefix: '/v2' });\n\nmodule.exports.handler = (event, context, callback) =\u003e {\n  api.run(event, context, callback);\n};\n```\n\n```javascript\n// routes/v1/products.js\nmodule.exports = (api, opts) =\u003e {\n  api.get('/product', handler_v1);\n};\n```\n\n```javascript\n// routes/v2/products.js\nmodule.exports = (api, opts) =\u003e {\n  api.get('/product', handler_v2);\n};\n```\n\nEven though both modules create a `/product` route, Lambda API will add the `prefix` to them, creating two unique routes. Your users can now access:\n\n- `/v1/product`\n- `/v2/product`\n\nYou can use `register()` as many times as you want AND it is recursive, so if you nest `register()` methods, the routes will build upon each other. For example:\n\n```javascript\nmodule.exports = (api, opts) =\u003e {\n  api.get('/product', handler_v1);\n  api.register(require('./v2/products.js'), { prefix: '/v2' });\n};\n```\n\nThis would create a `/v1/product` and `/v1/v2/product` route. You can also use `register()` to load routes from an external file without the `prefix`. This will just add routes to your `base` path. **NOTE:** Prefixed routes are built off of your `base` path if one is set. If your `base` was set to `/api`, then the first example above would produce the routes: `/api/v1/product` and `/api/v2/product`.\n\n## Debugging Routes\n\nLambda API has a `routes()` method that can be called on the main instance that will return an array containing the `METHOD` and full `PATH` of every configured route. This will include base paths and prefixed routes. This is helpful for debugging your routes.\n\n```javascript\nconst api = require('lambda-api')();\n\napi.get('/', (req, res) =\u003e {});\napi.post('/test', (req, res) =\u003e {});\n\napi.routes(); // =\u003e [ [ 'GET', '/' ], [ 'POST', '/test' ] ]\n```\n\nYou can also log the paths in table form to the console by passing in `true` as the only parameter.\n\n```javascript\n const api = require('lambda-api')()\n\n api.get('/', (req,res) =\u003e {})\n api.post('/test', (req,res) =\u003e {})\n\n api.routes(true)\n\n// Outputs to console\n╔═══════════╤═════════════════╗\n║  METHOD   │  ROUTE          ║\n╟───────────┼─────────────────╢\n║  GET      │  /              ║\n╟───────────┼─────────────────╢\n║  POST     │  /test          ║\n╚═══════════╧═════════════════╝\n```\n\n## REQUEST\n\nThe `REQUEST` object contains a parsed and normalized request from API Gateway. It contains the following values by default:\n\n- `app`: A reference to an instance of the app\n- `version`: The version set at initialization\n- `id`: The awsRequestId from the Lambda `context`\n- `interface`: The interface being used to access Lambda (`apigateway`,`alb`, or `edge`)\n- `params`: Dynamic path parameters parsed from the path (see [path parameters](#path-parameters))\n- `method`: The HTTP method of the request\n- `path`: The path passed in by the request including the `base` and any `prefix` assigned to routes\n- `query`: Querystring parameters parsed into an object\n- `multiValueQuery`: Querystring parameters with multiple values parsed into an object with array values\n- `headers`: An object containing the request headers (properties converted to lowercase for HTTP/2, see [rfc7540 8.1.2. HTTP Header Fields](https://tools.ietf.org/html/rfc7540)). Note that multi-value headers are concatenated with a comma per [rfc2616 4.2. Message Headers](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2).\n- `rawHeaders`: An object containing the original request headers (property case preserved)\n- `multiValueHeaders`: An object containing header values as multi-value arrays\n- `body`: The body of the request. If the `isBase64Encoded` flag is `true`, it will be decoded automatically.\n  - If the `content-type` header is `application/json`, it will attempt to parse the request using `JSON.parse()`\n  - If the `content-type` header is `application/x-www-form-urlencoded`, it will attempt to parse a URL encoded string using `querystring`\n  - Otherwise it will be plain text.\n- `rawBody`: If the `isBase64Encoded` flag is `true`, this is a copy of the original, base64 encoded body\n- `route`: The matched route of the request\n- `requestContext`: The `requestContext` passed from the API Gateway\n- `pathParameters`: The `pathParameters` passed from the API Gateway\n- `stageVariables`: The `stageVariables` passed from the API Gateway\n- `isBase64Encoded`: The `isBase64Encoded` boolean passed from the API Gateway\n- `auth`: An object containing the `type` and `value` of an authorization header. Currently supports `Bearer`, `Basic`, `OAuth`, and `Digest` schemas. For the `Basic` schema, the object is extended with additional fields for username/password. For the `OAuth` schema, the object is extended with key/value pairs of the supplied OAuth 1.0 values.\n- `namespace` or `ns`: A reference to modules added to the app's namespace (see [namespaces](#namespaces))\n- `cookies`: An object containing cookies sent from the browser (see the [cookie](#cookiename-value-options) `RESPONSE` method)\n- `context`: Reference to the `context` passed into the Lambda handler function\n- `coldStart`: Boolean that indicates whether or not the current invocation was a cold start\n- `requestCount`: Integer representing the total number of invocations of the current function container (how many times it has been reused)\n- `ip`: The IP address of the client making the request\n- `userAgent`: The `User-Agent` header sent by the client making the request\n- `clientType`: Either `desktop`, `mobile`, `tv`, `tablet` or `unknown` based on CloudFront's analysis of the `User-Agent` header\n- `clientCountry`: Two letter country code representing the origin of the requests as determined by CloudFront\n- `stack`: An array of function names executed as part of a route's [Execution Stack](#execution-stack), which is useful for debugging\n\nThe request object can be used to pass additional information through the processing chain. For example, if you are using a piece of authentication middleware, you can add additional keys to the `REQUEST` object with information about the user. See [middleware](#middleware) for more information.\n\n## RESPONSE\n\nThe `RESPONSE` object is used to send a response back to the API Gateway. The `RESPONSE` object contains several methods to manipulate responses. All methods are chainable unless they trigger a response.\n\n### status(code)\n\nThe `status` method allows you to set the status code that is returned to API Gateway. By default this will be set to `200` for normal requests or `500` on a thrown error. Additional built-in errors such as `404 Not Found` and `405 Method Not Allowed` may also be returned. The `status()` method accepts a single integer argument.\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  res.status(304).send('Not Modified');\n});\n```\n\n### sendStatus(code)\n\nThe `sendStatus` method sets the status code and returns its string representation as the response body. The `sendStatus()` method accepts a single integer argument.\n\n```javascript\nres.sendStatus(200); // equivalent to res.status(200).send('OK')\nres.sendStatus(304); // equivalent to res.status(304).send('Not Modified')\nres.sendStatus(403); // equivalent to res.status(403).send('Forbidden')\n```\n\n**NOTE:** If an unsupported status code is provided, it will return 'Unknown' as the body.\n\n### header(key, value [,append])\n\nThe `header` method allows for you to set additional headers to return to the client. By default, just the `content-type` header is sent with `application/json` as the value. Headers can be added or overwritten by calling the `header()` method with two string arguments. The first is the name of the header and then second is the value. You can utilize multi-value headers by specifying an array with multiple values as the `value`, or you can use an optional third boolean parameter and append multiple headers.\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  res.header('content-type', 'text/html').send('\u003cdiv\u003eThis is HTML\u003c/div\u003e');\n});\n\n// Set multiple header values\napi.get('/users', (req, res) =\u003e {\n  res.header('someHeader', ['foo', 'bar']).send({});\n});\n\n// Set multiple header by adding to existing header\napi.get('/users', (req, res) =\u003e {\n  res\n    .header('someHeader', 'foo')\n    .header('someHeader', 'bar', true) // append another value\n    .send({});\n});\n```\n\n**NOTE:** Header keys are converted and stored as lowercase in compliance with [rfc7540 8.1.2. HTTP Header Fields](https://tools.ietf.org/html/rfc7540) for HTTP/2. Header convenience methods (`getHeader`, `hasHeader`, and `removeHeader`) automatically ignore case.\n\n### getHeader(key [,asArray])\n\nRetrieve a specific header value. `key` is case insensitive. By default (and for backwards compatibility), header values are returned as a `string`. Multi-value headers will be concatenated using a comma (see [rfc2616 4.2. Message Headers](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2)). An optional second boolean parameter can be passed to return header values as an `array`.\n\n**NOTE:** The ability to retrieve the current header object by calling `getHeader()` is still possible, but the preferred method is to use the `getHeaders()` method. By default, `getHeader()` will return the object with `string` values.\n\n### getHeaders()\n\nRetrieve the current header object. Values are returned as `array`s.\n\n### hasHeader(key)\n\nReturns a boolean indicating the existence of `key` in the response headers. `key` is case insensitive.\n\n### removeHeader(key)\n\nRemoves header matching `key` from the response headers. `key` is case insensitive. This method is chainable.\n\n### getLink(s3Path [, expires] [, callback])\n\nThis returns a signed URL to the referenced file in S3 (using the `s3://{my-bucket}/{path-to-file}` format). You can optionally pass in an integer as the second parameter that will changed the default expiration time of the link. The expiration time is in seconds and defaults to `900`. In order to ensure proper URL signing, the `getLink()` must be asynchronous, and therefore returns a promise. You must either `await` the result or use a `.then` to retrieve the value.\n\nThere is an optional third parameter that takes an error handler callback. If the underlying `getSignedUrl()` call fails, the error will be returned using the standard `res.error()` method. You can override this by providing your own callback.\n\n```javascript\n// async/await\napi.get('/getLink', async (req, res) =\u003e {\n  let url = await res.getLink('s3://my-bucket/my-file.pdf');\n  return { link: url };\n});\n\n// promises\napi.get('/getLink', (req, res) =\u003e {\n  res.getLink('s3://my-bucket/my-file.pdf').then((url) =\u003e {\n    res.json({ link: url });\n  });\n});\n```\n\n### send(body)\n\nThe `send` methods triggers the API to return data to the API Gateway. The `send` method accepts one parameter and sends the contents through as is, e.g. as an object, string, integer, etc. AWS Gateway expects a string, so the data should be converted accordingly.\n\n### json(body)\n\nThere is a `json` convenience method for the `send` method that will set the headers to `application/json` as well as perform `JSON.stringify()` on the contents passed to it.\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  res.json({ message: 'This will be converted automatically' });\n});\n```\n\n### jsonp(body)\n\nThere is a `jsonp` convenience method for the `send` method that will set the headers to `application/json`, perform `JSON.stringify()` on the contents passed to it, and wrap the results in a callback function. By default, the callback function is named `callback`.\n\n```javascript\nres.jsonp({ foo: 'bar' });\n// =\u003e callback({ \"foo\": \"bar\" })\n\nres.status(500).jsonp({ error: 'some error' });\n// =\u003e callback({ \"error\": \"some error\" })\n```\n\nThe default can be changed by passing in `callback` as a URL parameter, e.g. `?callback=foo`.\n\n```javascript\n// ?callback=foo\nres.jsonp({ foo: 'bar' });\n// =\u003e foo({ \"foo\": \"bar\" })\n```\n\nYou can change the default URL parameter using the optional `callback` option when initializing the API.\n\n```javascript\nconst api = require('lambda-api')({ callback: 'cb' });\n\n// ?cb=bar\nres.jsonp({ foo: 'bar' });\n// =\u003e bar({ \"foo\": \"bar\" })\n```\n\n### html(body)\n\nThere is also an `html` convenience method for the `send` method that will set the headers to `text/html` and pass through the contents.\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  res.html('\u003cdiv\u003eThis is HTML\u003c/div\u003e');\n});\n```\n\n### type(type)\n\nSets the `content-type` header for you based on a single `String` input. There are thousands of MIME types, many of which are likely never to be used by your application. Lambda API stores a list of the most popular file types and will automatically set the correct `content-type` based on the input. If the `type` contains the \"/\" character, then it sets the `content-type` to the value of `type`.\n\n```javascript\nres.type('.html'); // =\u003e 'text/html'\nres.type('html'); // =\u003e 'text/html'\nres.type('json'); // =\u003e 'application/json'\nres.type('application/json'); // =\u003e 'application/json'\nres.type('png'); // =\u003e 'image/png'\nres.type('.doc'); // =\u003e 'application/msword'\nres.type('text/css'); // =\u003e 'text/css'\n```\n\nFor a complete list of auto supported types, see [mimemap.js](lib/mimemap.js). Custom MIME types can be added by using the `mimeTypes` option when instantiating Lambda API\n\n### location(path)\n\nThe `location` convenience method sets the `Location:` header with the value of a single string argument. The value passed in is not validated but will be encoded before being added to the header. Values that are already encoded can be safely passed in. Note that a valid `3xx` status code must be set to trigger browser redirection. The value can be a relative/absolute path OR a FQDN.\n\n```javascript\napi.get('/redirectToHome', (req, res) =\u003e {\n  res.location('/home').status(302).html('\u003cdiv\u003eRedirect to Home\u003c/div\u003e');\n});\n\napi.get('/redirectToGithub', (req, res) =\u003e {\n  res\n    .location('https://github.com')\n    .status(302)\n    .html('\u003cdiv\u003eRedirect to GitHub\u003c/div\u003e');\n});\n```\n\n### redirect([status,] path)\n\nThe `redirect` convenience method triggers a redirection and ends the current API execution. This method is similar to the `location()` method, but it automatically sets the status code and calls `send()`. The redirection URL (relative/absolute path, a FQDN, or an S3 path reference) can be specified as the only parameter or as a second parameter when a valid `3xx` status code is supplied as the first parameter. The status code is set to `302` by default, but can be changed to `300`, `301`, `302`, `303`, `307`, or `308` by adding it as the first parameter.\n\n```javascript\napi.get('/redirectToHome', (req, res) =\u003e {\n  res.redirect('/home');\n});\n\napi.get('/redirectToGithub', (req, res) =\u003e {\n  res.redirect(301, 'https://github.com');\n});\n\n// This will redirect a signed URL using the getLink method\napi.get('/redirectToS3File', (req, res) =\u003e {\n  res.redirect('s3://my-bucket/someFile.pdf');\n});\n```\n\n### cors([options])\n\nConvenience method for adding [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) headers to responses. An optional `options` object can be passed in to customize the defaults.\n\nThe six defined **CORS** headers are as follows:\n\n- Access-Control-Allow-Origin (defaults to `*`)\n- Access-Control-Allow-Methods (defaults to `GET, PUT, POST, DELETE, OPTIONS`)\n- Access-Control-Allow-Headers (defaults to `Content-Type, Authorization, Content-Length, X-Requested-With`)\n- Access-Control-Expose-Headers\n- Access-Control-Max-Age\n- Access-Control-Allow-Credentials\n\nThe `options` object can contain the following properties that correspond to the above headers:\n\n- origin _(string)_\n- methods _(string)_\n- headers _(string)_\n- exposeHeaders _(string)_\n- maxAge _(number in milliseconds)_\n- credentials _(boolean)_\n\nDefaults can be set by calling `res.cors()` with no properties, or with any combination of the above options.\n\n```javascript\nres.cors({\n  origin: 'example.com',\n  methods: 'GET, POST, OPTIONS',\n  headers: 'content-type, authorization',\n  maxAge: 84000000,\n});\n```\n\nYou can override existing values by calling `res.cors()` with just the updated values:\n\n```javascript\nres.cors({\n  origin: 'api.example.com',\n});\n```\n\n### error([code], message [,detail])\n\nAn error can be triggered by calling the `error` method. This will cause the API to stop execution and return the message to the client. The status code can be set by optionally passing in an integer as the first parameter. Additional detail can be added as an optional third parameter (or second parameter if no status code is passed). This will add an additional `detail` property to error logs. Details accepts any value that can be serialized by `JSON.stringify` including objects, strings and arrays. Custom error handling can be accomplished using the [Error Handling](#error-handling) feature.\n\n```javascript\napi.get('/users', (req, res) =\u003e {\n  res.error('This is an error');\n});\n\napi.get('/users', (req, res) =\u003e {\n  res.error(403, 'Not authorized');\n});\n\napi.get('/users', (req, res) =\u003e {\n  res.error('Error', { foo: 'bar' });\n});\n\napi.get('/users', (req, res) =\u003e {\n  res.error(404, 'Page not found', 'foo bar');\n});\n```\n\n### cookie(name, value [,options])\n\nConvenience method for setting cookies. This method accepts a `name`, `value` and an optional `options` object with the following parameters:\n\n| Property | Type                  | Description                                                                                                                                                                                                 |\n| -------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| domain   | `String`              | Domain name to use for the cookie. This defaults to the current domain.                                                                                                                                     |\n| expires  | `Date`                | The expiration date of the cookie. Local dates will be converted to GMT. Creates session cookie if this value is not specified.                                                                             |\n| httpOnly | `Boolean`             | Sets the cookie to be accessible only via a web server, not JavaScript.                                                                                                                                     |\n| maxAge   | `Number`              | Set the expiration time relative to the current time in milliseconds. Automatically sets the `expires` property if not explicitly provided.                                                                 |\n| path     | `String`              | Path for the cookie. Defaults to \"/\" for the root directory.                                                                                                                                                |\n| secure   | `Boolean`             | Sets the cookie to be used with HTTPS only.                                                                                                                                                                 |\n| sameSite | `Boolean` or `String` | Sets the SameSite value for cookie. `true` or `false` sets `Strict` or `Lax` respectively. Also allows a string value. See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1 |\n\nThe `name` attribute should be a string (auto-converted if not), but the `value` attribute can be any type of value. The `value` will be serialized (if an object, array, etc.) and then encoded using `encodeURIComponent` for safely assigning the cookie value. Cookies are automatically parsed, decoded, and available via the `REQUEST` object (see [REQUEST](#request)).\n\n**NOTE:** The `cookie()` method only sets the header. A execution ending method like `send()`, `json()`, etc. must be called to send the response.\n\n```javascript\nres.cookie('foo', 'bar', { maxAge: 3600 * 1000, secure: true }).send();\nres\n  .cookie(\n    'fooObject',\n    { foo: 'bar' },\n    { domain: '.test.com', path: '/admin', httpOnly: true }\n  )\n  .send();\nres\n  .cookie('fooArray', ['one', 'two', 'three'], { path: '/', httpOnly: true })\n  .send();\n```\n\n### clearCookie(name [,options])\n\nConvenience method for expiring cookies. Requires the `name` and optional `options` object as specified in the [cookie](#cookiename-value-options) method. This method will automatically set the expiration time. However, most browsers require the same options to clear a cookie as was used to set it. E.g. if you set the `path` to \"/admin\" when you set the cookie, you must use this same value to clear it.\n\n```javascript\nres.clearCookie('foo', { secure: true }).send();\nres\n  .clearCookie('fooObject', {\n    domain: '.test.com',\n    path: '/admin',\n    httpOnly: true,\n  })\n  .send();\nres.clearCookie('fooArray', { path: '/', httpOnly: true }).send();\n```\n\n**NOTE:** The `clearCookie()` method only sets the header. A execution ending method like `send()`, `json()`, etc. must be called to send the response.\n\n### etag([boolean])\n\nEnables Etag generation for the response if at value of `true` is passed in. Lambda API will generate an Etag based on the body of the response and return the appropriate header. If the request contains an `If-No-Match` header that matches the generated Etag, a `304 Not Modified` response will be returned with a blank body.\n\n### cache([age] [, private])\n\nAdds `cache-control` header to responses. If the first parameter is an `integer`, it will add a `max-age` to the header. The number should be in milliseconds. If the first parameter is `true`, it will add the cache headers with `max-age` set to `0` and use the current time for the `expires` header. If set to false, it will add a cache header with `no-cache, no-store, must-revalidate` as the value. You can also provide a custom string that will manually set the value of the `cache-control` header. And optional second argument takes a `boolean` and will set the `cache-control` to `private` This method is chainable.\n\n```javascript\nres.cache(false).send(); // 'cache-control': 'no-cache, no-store, must-revalidate'\nres.cache(1000).send(); // 'cache-control': 'max-age=1'\nres.cache(30000, true).send(); // 'cache-control': 'private, max-age=30'\n```\n\n### modified(date)\n\nAdds a `last-modified` header to responses. A value of `true` will set the value to the current date and time. A JavaScript `Date` object can also be passed in. Note that it will be converted to UTC if not already. A `string` can also be passed in and will be converted to a date if JavaScript's `Date()` function is able to parse it. A value of `false` will prevent the header from being generated, but will not remove any existing `last-modified` headers.\n\n### attachment([filename])\n\nSets the HTTP response `content-disposition` header field to \"attachment\". If a `filename` is provided, then the `content-type` is set based on the file extension using the `type()` method and the \"filename=\" parameter is added to the `content-disposition` header.\n\n```javascript\nres.attachment();\n// content-disposition: attachment\n\nres.attachment('path/to/logo.png');\n// content-disposition: attachment; filename=\"logo.png\"\n// content-type: image/png\n```\n\n### download(file [, filename] [, options] [, callback])\n\nThis transfers the `file` (either a local path, S3 file reference, or Javascript `Buffer`) as an \"attachment\". This is a convenience method that combines `attachment()` and `sendFile()` to prompt the user to download the file. This method optionally takes a `filename` as a second parameter that will overwrite the \"filename=\" parameter of the `content-disposition` header, otherwise it will use the filename from the `file`. An optional `options` object passes through to the [sendFile()](#sendfilefile--options--callback) method and takes the same parameters. Finally, a optional `callback` method can be defined which is passed through to [sendFile()](#sendfilefile--options--callback) as well.\n\n```javascript\nres.download('./files/sales-report.pdf')\n\nres.download('./files/sales-report.pdf', 'report.pdf')\n\nres.download('s3://my-bucket/path/to/file.png', 'logo.png', { maxAge: 3600000 })\n\nres.download(\u003cBuffer\u003e, 'my-file.docx', { maxAge: 3600000 }, (err) =\u003e {\n  if (err) {\n    res.error('Custom File Error')\n  }\n})\n```\n\n### sendFile(file [, options] [, callback])\n\nThe `sendFile()` method takes up to three arguments. The first is the `file`. This is either a local filename (stored within your uploaded lambda code), a reference to a file in S3 (using the `s3://{my-bucket}/{path-to-file}` format), or a JavaScript `Buffer`. You can optionally pass an `options` object using the properties below as well as a callback function `callback(err)` that can handle custom errors or manipulate the response before sending to the client.\n\n| Property     | Type                  | Description                                                                                                                                                                | Default |\n| ------------ | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |\n| maxAge       | `Number`              | Set the expiration time relative to the current time in milliseconds. Automatically sets the `Expires` header                                                              | 0       |\n| root         | `String`              | Root directory for relative filenames.                                                                                                                                     |         |\n| lastModified | `Boolean` or `String` | Sets the `last-modified` header to the last modified date of the file. This can be disabled by setting it to `false`, or overridden by setting it to a valid `Date` object |         |\n| headers      | `Object`              | Key value pairs of additional headers to be sent with the file                                                                                                             |         |\n| cacheControl | `Boolean` or `String` | Enable or disable setting `cache-control` response header. Override value with custom string.                                                                              | true    |\n| private      | `Boolean`             | Sets the `cache-control` to `private`.                                                                                                                                     | false   |\n\n```javascript\nres.sendFile('./img/logo.png')\n\nres.sendFile('./img/logo.png', { maxAge: 3600000 })\n\nres.sendFile('s3://my-bucket/path/to/file.png', { maxAge: 3600000 })\n\nres.sendFile(\u003cBuffer\u003e, 'my-file.docx', { maxAge: 3600000 }, (err) =\u003e {\n  if (err) {\n    res.error('Custom File Error')\n  }\n})\n```\n\nThe `callback` function supports returning a promise, allowing you to perform additional tasks _after_ the file is successfully loaded from the source. This can be used to perform additional synchronous tasks before returning control to the API execution.\n\n**NOTE:** In order to access S3 files, your Lambda function must have `GetObject` access to the files you're attempting to access.\n\nSee [Enabling Binary Support](#enabling-binary-support) for more information.\n\n## Enabling Binary Support\n\nTo enable binary support, you need to add `*/*` under \"Binary Media Types\" in **API Gateway** -\u003e **APIs** -\u003e **[ your api ]** -\u003e **Settings**. This will also `base64` encode all body content, but Lambda API will automatically decode it for you.\n\n![Binary Media Types](http://jeremydaly.com//lambda-api/binary-media-types.png)\n_Add_ `*/*` _to Binary Media Types_\n\n## Path Parameters\n\nPath parameters are extracted from the path sent in by API Gateway. Although API Gateway supports path parameters, the API doesn't use these values but insteads extracts them from the actual path. This gives you more flexibility with the API Gateway configuration. Path parameters are defined in routes using a colon `:` as a prefix.\n\n```javascript\napi.get('/users/:userId', (req, res) =\u003e {\n  res.send('User ID: ' + req.params.userId);\n});\n```\n\nPath parameters act as wildcards that capture the value into the `params` object. The example above would match `/users/123` and `/users/test`. The system always looks for static paths first, so if you defined paths for `/users/test` and `/users/:userId`, exact path matches would take precedence. Path parameters only match the part of the path they are defined on. E.g. `/users/456/test` would not match `/users/:userId`. You would either need to define `/users/:userId/test` as its own path, or create another path with an additional path parameter, e.g. `/users/:userId/:anotherParam`.\n\nA path can contain as many parameters as you want. E.g. `/users/:param1/:param2/:param3`.\n\n## Wildcard Routes\n\nWildcard routes are supported for matching arbitrary paths. Wildcards only work at the _end of a route definition_ such as `/*` or `/users/*`. Wildcards within a path, e.g. `/users/*/posts` are not supported. Wildcard routes do support parameters, however, so `/users/:id/*` would capture the `:id` parameter in your wildcard handler.\n\nWildcard routes will match any deep paths after the wildcard. For example, a `GET` method for path `/users/*` would match `/users/1/posts/latest`. The only exception is for the `OPTIONS` method. A path **must** exist for a wildcard on an `OPTIONS` route in order to execute the handler. If a wildcard route is defined for another method higher up the path, then the `OPTIONS` handler will fire. For example, if there was a `POST` method defined on `/users/*`, then an `OPTIONS` method for `/users/2/posts/*` would fire as it assumes that the `POST` path would exist.\n\nIn most cases, [Path Parameters](#path-parameters) should be used in favor of wildcard routes. However, if you need to support unpredictable path lengths, or your are building single purpose functions and will be mapping routes from API Gateway, the wildcards are a powerful pattern. Another good use case is to use the `OPTIONS` method to provide CORS headers.\n\n```javascript\napi.options('/*', (req, res) =\u003e {\n  // Return CORS headers\n  res.cors().send({});\n});\n```\n\n## Logging\n\nLambda API includes a robust logging engine specifically designed to utilize native JSON support for CloudWatch Logs. Not only is it ridiculously fast, but it's also highly configurable. Logging is disabled by default, but can be enabled by passing `{ logger: true }` when you create the Lambda API instance (or by passing a [Logging Configuration](#logging-configuration) definition).\n\nThe logger is attached to the `REQUEST` object and can be used anywhere the object is available (e.g. routes, middleware, and error handlers).\n\n```javascript\nconst api = require('lambda-api')({ logger: true });\n\napi.get('/status', (req, res) =\u003e {\n  req.log.info('Some info about this route');\n  res.send({ status: 'ok' });\n});\n```\n\nIn addition to manual logging, Lambda API can also generate \"access\" logs for your API requests. API Gateway can also provide access logs, but they are limited to contextual information about your request (see [here](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html)). Lambda API allows you to capture the same data **PLUS** additional information directly from within your application.\n\n### Logging Configuration\n\nLogging can be enabled by setting the `logger` option to `true` when creating the Lambda API instance. Logging can be configured by setting `logger` to an object that contains configuration information. The following table contains available logging configuration properties.\n\n| Property     | Type                    | Description                                                                                                                                                                                | Default       |\n| ------------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |\n| access       | `boolean` or `string`   | Enables/disables automatic access log generation for each request. See [Access Logs](#access-logs).                                                                                        | `false`       |\n| errorLogging | `boolean`               | Enables/disables automatic error logging.                                                                                                                                                  | `true`        |\n| customKey    | `string`                | Sets the JSON property name for custom data passed to logs.                                                                                                                                | `custom`      |\n| detail       | `boolean`               | Enables/disables adding `REQUEST` and `RESPONSE` data to all log entries.                                                                                                                  | `false`       |\n| level        | `string`                | Minimum logging level to send logs for. See [Logging Levels](#logging-levels).                                                                                                             | `info`        |\n| levels       | `object`                | Key/value pairs of custom log levels and their priority. See [Custom Logging Levels](#custom-logging-levels).                                                                              |               |\n| log          | `function`              | Custom function for overriding standard `console.log`.                                                                                                                                     | `console.log` |\n| messageKey   | `string`                | Sets the JSON property name of the log \"message\".                                                                                                                                          | `msg`         |\n| multiValue   | `boolean`               | Enables multi-value support for querystrings. If enabled, the `qs` parameter will return all values as `array`s and will include multiple values if they exist.                            | `false`       |\n| nested       | `boolean`               | Enables/disables nesting of JSON logs for serializer data. See [Serializers](#serializers).                                                                                                | `false`       |\n| timestamp    | `boolean` or `function` | By default, timestamps will return the epoch time in milliseconds. A value of `false` disables log timestamps. A function that returns a value can be used to override the default format. | `true`        |\n| sampling     | `object`                | Enables log sampling for periodic request tracing. See [Sampling](#sampling).                                                                                                              |               |\n| serializers  | `object`                | Adds serializers that manipulate the log format. See [Serializers](#serializers).                                                                                                          |               |\n| stack        | `boolean`               | Enables/disables the inclusion of stack traces in caught errors.                                                                                                                           | `false`       |\n\nExample:\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    level: 'debug',\n    access: true,\n    customKey: 'detail',\n    messageKey: 'message',\n    timestamp: () =\u003e new Date().toUTCString(), // custom timestamp\n    stack: true,\n  },\n});\n```\n\n### Log Format\n\nLogs are generated using Lambda API's standard JSON format. The log format can be customized using [Serializers](#serializers).\n\n**Standard log format (manual logging):**\n\n```javascript\n  {\n    \"level\": \"info\", // log level\n    \"time\": 1534724904910, // request timestamp\n    \"id\": \"41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9\", // awsRequestId\n    \"route\": \"/user/:userId\", // route accessed\n    \"method\": \"GET\", // request method\n    \"msg\": \"Some info about this route\", // log message\n    \"timer\": 2, // execution time up until log was generated\n    \"custom\": \"additional data\", // addditional custom log detail\n    \"remaining\": 2000, // remaining milliseconds until function timeout\n    \"function\": \"my-function-v1\", // function name\n    \"memory\": 2048, // allocated function memory\n    \"int\": \"apigateway\", // interface used to access the Lambda function\n    \"sample\": true // is generated during sampling request?\n  }\n```\n\n### Access Logs\n\nAccess logs generate detailed information about the API request. Access logs are disabled by default, but can be enabled by setting the `access` property to `true` in the logging configuration object. If set to `false`, access logs will _only_ be generated when other log entries (`info`, `error`, etc.) are created. If set to the string `'never'`, access logs will never be generated.\n\nAccess logs use the same format as the standard logs above, but include additional information about the request. The access log format can be customized using [Serializers](#serializers).\n\n**Access log format (automatic logging):**\n\n```javascript\n  {\n    ... Standard Log Data ...,\n    \"path\": \"/user/123\", // path accessed\n    \"ip\": \"12.34.56.78\", // client ip address\n    \"ua\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)...\", // User-Agent\n    \"version\": \"v1\", // specified API version\n    \"device\": \"mobile\", // client device (as determined by CloudFront)\n    \"country\": \"US\", // client country (as determined by CloudFront)\n    \"qs\": { // query string parameters\n      \"foo\": \"bar\"\n    }\n  }\n```\n\n### Logging Levels\n\nLogging \"levels\" allow you to add detailed logging to your functions based on severity. There are six standard log levels as specified in the table below along with their default priority.\n\n| Level   | Priority |\n| ------- | -------- |\n| `trace` | 10       |\n| `debug` | 20       |\n| `info`  | 30       |\n| `warn`  | 40       |\n| `error` | 50       |\n| `fatal` | 60       |\n\nLogs are written to CloudWatch Logs _ONLY_ if they are the same or higher severity than specified in the `level` log configuration.\n\n```javascript\n// Logging level set to \"warn\"\nconst api = require('lambda-api')({ logger: { level: 'warn' } });\n\napi.get('/', (req, res) =\u003e {\n  req.log.trace('trace log message'); // ignored\n  req.log.debug('debug log message'); // ignored\n  req.log.info('info log message'); // ignored\n  req.log.warn('warn log message'); // write to CloudWatch\n  req.log.error('error log message'); // write to CloudWatch\n  req.log.fatal('fatal log message'); // write to CloudWatch\n  res.send({ hello: 'world' });\n});\n```\n\n### Custom Logging Levels\n\nCustom logging \"levels\" can be added by specifying an object containing \"level names\" as keys and their priorities as values. You can also adjust the priority of standard levels by adding it to the object.\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    levels: {\n      test: 5, // low priority 'test' level\n      customLevel: 35, // between info and warn\n      trace: 70, // set trace to the highest priority\n    },\n  },\n});\n```\n\nIn the example above, the `test` level would only generate logs if the priority was set to `test`. `customLevel` would generate logs if `level` was set to anything with the same or lower priority (e.g. `info`). `trace` now has the highest priority and would generate a log entry no matter what the level was set to.\n\n### Adding Additional Detail\n\nManual logging also allows you to specify additional detail with each log entry. Details can be added by suppling _any variable type_ as a second parameter to the logger function.\n\n```javascript\nreq.log.info('This is the main log message', 'some other detail'); // string\nreq.log.info('This is the main log message', {\n  foo: 'bar',\n  isAuthorized: someVar,\n}); // object\nreq.log.info('This is the main log message', 25); // number\nreq.log.info('This is the main log message', ['val1', 'val2', 'val3']); // array\nreq.log.info('This is the main log message', true); // boolean\n```\n\nIf an `object` is provided, the keys will be merged into the main log entry's JSON. If any other `type` is provided, the value will be assigned to a key using the the `customKey` setting as its property name. If `nested` is set to `true`, objects will be nested under the value of `customKey` as well.\n\n### Serializers\n\nSerializers allow you to customize log formats as well as add additional data from your application. Serializers can be defined by adding a `serializers` property to the `logger` configuration object. A property named for an available serializer (`main`, `req`, `res`, `context` or `custom`) needs to return an anonymous function that takes one argument and returns an object. The returned object will be merged into the main JSON log entry. Existing properties can be removed by returning `undefined` as their values.\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    serializers: {\n      req: (req) =\u003e {\n        return {\n          apiId: req.requestContext.apiId, // add the apiId\n          stage: req.requestContext.stage, // add the stage\n          qs: undefined, // remove the query string\n        };\n      },\n    },\n  },\n});\n```\n\nSerializers are passed one argument that contains their corresponding object. `req` _and_ `main` receive the `REQUEST` object, `res` receives the `RESPONSE` object, `context` receives the `context` object passed into the main `run` function, and `custom` receives custom data passed in to the logging methods. Note that only custom `objects` will trigger the `custom` serializer.\n\nIf the `nested` option is set to true in the `logger` configuration, then JSON log entries will be generated with properties for `req`, `res`, `context` and `custom` with their serialized data as nested objects.\n\n### Sampling\n\nSampling allows you to periodically generate log entries for all possible severities within a single request execution. All of the log entries will be written to CloudWatch Logs and can be used to trace an entire request. This can be used for debugging, metric samples, resource response time sampling, etc.\n\nSampling can be enabled by adding a `sampling` property to the `logger` configuration object. A value of `true` will enable the default sampling rule. The default can be changed by passing in a configuration object with the following available _optional_ properties:\n\n| Property | Type     | Description                                                              | Default |\n| -------- | -------- | ------------------------------------------------------------------------ | ------- |\n| target   | `number` | The minimum number of samples per `period`.                              | 1       |\n| rate     | `number` | The percentage of samples to be taken during the `period`.               | 0.1     |\n| period   | `number` | Number of **seconds** representing the duration of each sampling period. | 60      |\n\nThe example below would sample at least `2` requests every `30` seconds as well as an additional `0.1` (10%) of all other requests during that period. Lambda API tracks the velocity of requests and attempts to distribute the samples as evenly as possible across the specified `period`.\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    sampling: {\n      target: 2,\n      rate: 0.1,\n      period: 30,\n    },\n  },\n});\n```\n\nAdditional rules can be added by specifying a `rules` parameter in the `sampling` configuration object. The `rules` should contain an `array` of \"rule\" objects with the following properties:\n\n| Property | Type                | Description                                                              | Default | Required |\n| -------- | ------------------- | ------------------------------------------------------------------------ | ------- | -------- |\n| route    | `string`            | The route (as defined in a route handler) to apply this rule to.         |         | **Yes**  |\n| target   | `number`            | The minimum number of samples per `period`.                              | 1       | No       |\n| rate     | `number`            | The percentage of samples to be taken during the `period`.               | 0.1     | No       |\n| period   | `number`            | Number of **seconds** representing the duration of each sampling period. | 60      | No       |\n| method   | `string` or `array` | A comma separated list or `array` of HTTP methods to apply this rule to. |         | No       |\n\nThe `route` property is the only value required and must match a route's path definition (e.g. `/user/:userId`, not `/user/123`) to be activated. Routes can also use wildcards at the end of the route to match multiple routes (e.g. `/user/*` would match `/user/:userId` _AND_ `/user/:userId/tags`). A list of `method`s can also be supplied that would limit the rule to just those HTTP methods. A comma separated `string` or an `array` will be properly parsed.\n\nSampling rules can be used to disable sampling on certain routes by setting the `target` and `rate` to `0`. For example, if you had a `/status` route that you didn't want to be sampled, you would use the following configuration:\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    sampling: {\n      rules: [{ route: '/status', target: 0, rate: 0 }],\n    },\n  },\n});\n```\n\nYou could also use sampling rules to enable sampling on certain routes:\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    sampling: {\n      rules: [\n        { route: '/user', target: 1, rate: 0.1 }, // enable for /user route\n        { route: '/posts/*', target: 1, rate: 0.1 }, // enable for all routes that start with /posts\n      ],\n      target: 0, // disable sampling default target\n      rate: 0, // disable sampling default rate\n    },\n  },\n});\n```\n\nIf you'd like to disable sampling for `GET` and `POST` requests to user:\n\n```javascript\nconst api = require('lambda-api')({\n  logger: {\n    sampling: {\n      rules: [\n        // disable GET and POST on /user route\n        { route: '/user', target: 0, rate: 0, method: ['GET', 'POST'] },\n      ],\n    },\n  },\n});\n```\n\nAny combination of rules can be provided to customize sampling behavior. Note that each rule tracks requests and velocity separately, which could limit the number of samples for infrequently accessed routes.\n\n## Middleware\n\nThe API supports middleware to preprocess requests before they execute their matching routes. Global middleware is defined using the `use` method one or more functions with three parameters for the `REQUEST`, `RESPONSE`, and `next` callback. For example:\n\n```javascript\napi.use((req, res, next) =\u003e {\n  // do something\n  next();\n});\n```\n\nMiddleware can be used to authenticate requests, create database connections, etc. The `REQUEST` and `RESPONSE` objects behave as they do within routes, allowing you to manipulate either object. In the case of authentication, for example, you could verify a request and update the `REQUEST` with an `authorized` flag and continue execution. Or if the request couldn't be authorized, you could respond with an error directly from the middleware. For example:\n\n```javascript\n// Auth User\napi.use((req, res, next) =\u003e {\n  if (req.headers.authorization === 'some value') {\n    req.authorized = true;\n    next(); // continue execution\n  } else {\n    res.error(401, 'Not Authorized');\n  }\n});\n```\n\nThe `next()` callback tells the system to continue executing. If this is not called then the system will hang (and eventually timeout) unless another request ending call such as `error` is called. You can define as many middleware functions as you want. They will execute serially and synchronously in the order in which they are defined.\n\n**NOTE:** Middleware can use either callbacks like `res.send()` or `return` to trigger a response to the user. Please note that calling either one of these from within a middleware function will return the response immediately and terminate API execution.\n\n### Restricting middleware execution to certain path(s)\n\nBy default, middleware will execute on every path. If you only need it to execute for specific paths, pass the path (or array of paths) as the first parameter to the `use` method.\n\n```javascript\n// Single path\napi.use('/users', (req, res, next) =\u003e {\n  next();\n});\n\n// Wildcard path\napi.use('/users/*', (req, res, next) =\u003e {\n  next();\n});\n\n// Multiple path\napi.use(['/users', '/posts'], (req, res, next) =\u003e {\n  next();\n});\n\n// Parameterized paths\napi.use('/users/:userId', (req, res, next) =\u003e {\n  next();\n});\n\n// Multiple paths with parameters and wildcards\napi.use(['/comments', '/users/:userId', '/posts/*'], (req, res, next) =\u003e {\n  next();\n});\n```\n\n**NOTE:** Path matching checks the defined `route`. This means that parameterized paths must be matched by the parameter (e.g. `/users/:param1`).\n\n### Specifying multiple middleware\n\nIn addition to restricting middleware to certain paths, you can also add multiple middleware using a single `use` method. This is a convenient way to assign several pieces of middleware to the same path or minimize your code.\n\n```javascript\nconst middleware1 = (req, res, next) =\u003e {\n  // middleware code\n};\n\nconst middleware2 = (req, res, next) =\u003e {\n  // some other middleware code\n};\n\n// Restrict middleware1 and middleware2 to /users route\napi.use('/users', middleware1, middleware2);\n\n// Add middleware1 and middleware2 to all routes\napi.use(middleware1, middleware2);\n```\n\n### Method-based middleware\n\nMiddleware can be restricted to a specific method (or array of methods) by using the route convenience methods or `METHOD`. Method-based middleware behaves exactly like global middleware, requiring a `REQUEST`, `RESPONSE`, and `next` parameter. You can specify multiple middlewares for each method/path using a single method call, or by using multiple method calls. Lambda API will merge the [execution stacks](#execution-stacks) for you.\n\n```javascript\nconst middleware1 = (req, res, next) =\u003e {\n  // middleware code\n};\n\nconst middleware2 = (req, res, next) =\u003e {\n  // middleware code\n};\n\n// Execute middleware1 and middleware2 on /users route\napi.get('/users', middleware1, middleware2, (req, res) =\u003e {\n  // handler function\n});\n\n// Execute middleware1 on /users route\napi.get('/users', middleware1);\n\n// Add middleware2 and handler\napi.get('/users', middleware2, (req, res) =\u003e {\n  // handler function\n});\n```\n\n## Clean Up\n\nThe API has a built-in clean up method called 'finally()' that will execute after all middleware and routes have been completed, but before execution is complete. This can be used to close database connections or to perform other clean up functions. A clean up function can be defined using the `finally` method and requires a function with two parameters for the REQUEST and the RESPONSE as its only argument. For example:\n\n```javascript\napi.finally((req, res) =\u003e {\n  // close unneeded database connections and perform clean up\n});\n```\n\nThe `RESPONSE` **CANNOT** be manipulated since it has already been generated. Only one `finally()` method can be defined and will execute after properly handled errors as well.\n\n## Error Handling\n\nLambda API has sophisticated error handling that will automatically catch and log errors using the [Logging](#logging) system. By default, errors will trigger a JSON response with the error message. If you would like to define additional error handling, you can define them using the `use` method similar to middleware. Error handling middleware must be defined as a function with **four** arguments instead of three like normal middleware. An additional `error` parameter must be added as the first parameter. This will contain the error object generated.\n\n```javascript\napi.use((err, req, res, next) =\u003e {\n  // do something with the error\n  next();\n});\n```\n\nThe `next()` callback will cause the script to continue executing and eventually call the standard error handling function. You can short-circuit the default handler by calling a request ending method such as `send`, `html`, or `json` OR by `return`ing data from your handler.\n\nError handling middleware, like regular middleware, also supports specifying multiple handlers in a single `use` method call.\n\n```javascript\nconst errorHandler1 = (err,req,res,next) =\u003e {\n  // do something with the error\n  next()\n})\n\nconst errorHandler2 = (err,req,res,next) =\u003e {\n  // do something else with the error\n  next()\n})\n\napi.use(errorHandler1,errorHandler2)\n```\n\n**NOTE:** Error handling middleware runs on _ALL_ paths. If paths are passed in as the first parameter, they will be ignored by the error handling middleware.\n\n### Error Types\n\nLambda API provides several different types of errors that can be used by your application. `ApiError`, `RouteError`, `MethodError`, `ResponseError`, and `FileError` will all be passed to your error middleware. `ConfigurationError`s will throw an exception when you attempt to `.run()` your route and can be caught in a `try/catch` block. Most error types contain additional properties that further detail the issue.\n\n```javascript\nconst errorHandler = (err,req,res,next) =\u003e {\n\n  if (err.name === 'RouteError') {\n    // do something with route error\n  } else if (err.name === 'FileError') {\n    // do something with file error\n  }\n  // continue\n  next()\n})\n```\n\n### Error Logging\n\nError logs are generated using either the `error` or `fatal` logging level. Errors can be triggered from within routes and middleware by calling the `error()` method on the `RESPONSE` object. If provided a `string` as an error message, this will generate an `error` level log entry. If you supply a JavaScript `Error` object, or you `throw` an error, a `fatal` log entry will be generated.\n\n```javascript\napi.get('/somePath', (res, req) =\u003e {\n  res.error('This is an error message'); // creates 'error' log\n});\n\napi.get('/someOtherPath', (res, req) =\u003e {\n  res.error(new Error('This is a fatal error')); // creates 'fatal' log\n});\n\napi.get('/anotherPath', (res, req) =\u003e {\n  throw new Error('Another fatal error'); // creates 'fatal' log\n});\n\napi.get('/finalPath', (res, req) =\u003e {\n  try {\n    // do something\n  } catch (e) {\n    res.error(e); // creates 'fatal' log\n  }\n});\n```\n\n## Namespaces\n\nLambda API allows you to map specific modules to namespaces that can be accessed from the `REQUEST` object. This is helpful when using the pattern in which you create a module that exports middleware, error, or route functions. In the example below, the `data` namespace is added to the API and then accessed by reference within an included module.\n\nThe main handler file might look like this:\n\n```javascript\n// Use app() function to add 'data' namespace\napi.app('data', require('./lib/data.js'));\n\n// Create a get route to load user details\napi.get('/users/:userId', require('./lib/users.js'));\n```\n\nThe users.js module might look like this:\n\n```javascript\nmodule.exports = (req, res) =\u003e {\n  let userInfo = req.namespace.data.getUser(req.params.userId);\n  res.json({ userInfo: userInfo });\n};\n```\n\nBy saving references in namespaces, you can access them without needing to require them in every module. Namespaces can be added using the `app()` method of the API. `app()` accepts either two parameters: a string representing the name of the namespace and a function reference _OR_ an object with string names as keys and function references as the values. For example:\n\n```javascript\napi.app('namespace', require('./lib/ns-functions.js'));\n\n// OR\n\napi.app({\n  namespace1: require('./lib/ns1-functions.js'),\n  namespace2: require('./lib/ns2-functions.js'),\n});\n```\n\n## CORS Support\n\nCORS can be implemented using the [wildcard routes](#wildcard-routes) feature. A typical implementation would be as follows:\n\n```javascript\napi.options('/*', (req, res) =\u003e {\n  // Add CORS headers\n  res.header('Access-Control-Allow-Origin', '*');\n  res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');\n  res.header(\n    'Access-Control-Allow-Headers',\n    'Content-Type, Authorization, Content-Length, X-Requested-With'\n  );\n  res.status(200).send({});\n});\n```\n\nYou can also use the `cors()` ([see here](#corsoptions)) convenience method to add CORS headers.\n\nConditional route support could be added via middleware or with conditional logic within the `OPTIONS` route.\n\n## Compression\n\nCurrently, API Gateway HTTP APIs do not support automatic compression, but that doesn't mean the Lambda can't return a compressed response. Lambda API supports compression out of the box:\n\n```javascript\nconst api = require('lambda-api')({\n  compression: true,\n});\n```\n\nThe response will automatically be compressed based on the `Accept-Encoding` header in the request. Supported compressions are Gzip and Deflate, with opt-in support for Brotli:\n\n```javascript\nconst api = require('lambda-api')({\n  compression: ['br', 'gzip'],\n});\n```\n\n\u003e Note: Brotli compression is significantly slower than Gzip due to its CPU intensive algorithm. Please test extensively before enabling on a production environment.\n\nFor full control over the response compression, instantiate the API with `isBase64` set to true, and a custom serializer that returns a compressed response as a base64 encoded string. Also, don't forget to set the correct `content-encoding` header:\n\n```javascript\nconst zlib = require('zlib');\n\nconst api = require('lambda-api')({\n  isBase64: true,\n  headers: {\n    'content-encoding': ['gzip'],\n  },\n  serializer: (body) =\u003e {\n    const json = JSON.stringify(body);\n    return zlib.gzipSync(json).toString('base64');\n  },\n});\n```\n\n## Execution Stacks\n\nLambda API v0.10 introduced execution stacks as a way to more efficiently process middleware. Execution stacks are automatically created for you when adding routes and middleware using the standard route convenience methods, as well as `METHOD()` and `use()`. This is a technical implementation that has made method-based middleware and additional wildcard functionality possible.\n\nExecution stacks are backwards compatible, so no code changes need to be made when upgrading from a lower version. The only caveat is with matching middleware to specific parameterized paths. Path-based middleware creates mount points that require methods to execute. This means that a `/users/:userId` middleware path would not execute if you defined a `/users/test` path.\n\nExecution stacks allow you to execute multiple middlewares based on a number of factors including path and method. For example, you can specify a global middleware to run on every `/user/*` route, with additional middleware running on just `/user/settings/*` routes, with more middleware running on just `GET` requests to `/users/settings/name`. Execution stacks inherit middleware from matching routes and methods higher up the stack, building a final stack that is unique to each route. Definition order also matters, meaning that routes defined _before_ global middleware **will not** have it as part of its execution stack. The same is true of any wildcard-based route, giving you flexibility and control over when middleware is applied.\n\nFor debugging purposes, a new `REQUEST` property called `stack` has been added. If you name your middleware functions (either by assigning them to variables or using standard named functions), the `stack` property will return an array that lists the function names of the execution stack in processing order.\n\n## Lambda Proxy Integration\n\nLambda Proxy Integration is an option in API Gateway that allows the details of an API request to be passed as the `event` parameter of a Lambda function. A typical API Gateway request event with Lambda Proxy Integration enabled can be found [here](https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-api-gateway-request).\n\nLambda API automatically parses this information to create a normalized `REQUEST` object. The request can then be routed using the APIs methods.\n\n## ALB Integration\n\nAWS recently added support for Lambda functions as targets for Application Load Balancers. While the events from ALBs are similar to API Gateway, there are a number of differences that would require code changes based on implementation. Lambda API detects the event `interface` and automatically normalizes the `REQUEST` object. It also correctly formats the `RESPONSE` (supporting both multi-header and non-multi-header mode) for you. This allows you to call your Lambda function from API Gateway, ALB, or both, without requiring any code changes.\n\nPlease note that ALB events do not contain all of the same headers as API Gateway (such as `clientType`), but Lambda API provides defaults for seamless integration between the interfaces. ALB also automatically enables binary support, giving you the ability to serve images and other binary file types. Lambda API reads the `path` parameter supplied by the ALB event and uses that to route your requests. If you specify a wildcard in your listener rule, then all matching paths will be forwarded to your Lambda function. Lambda API's routing system can be used to process these routes just like with API Gateway. This includes static paths, parameterized paths, wildcards, middleware, etc.\n\nSample ALB request and response events can be found [here](https://docs.aws.amazon.com/lambda/latest/dg/services-alb.html).\n\n## Configuring Routes in API Gateway\n\nRoutes must be configured in API Gateway in order to support routing to the Lambda function. The easiest way to support all of your routes without recreating them is to use [API Gateway's Proxy Integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-proxy-resource?icmpid=docs_apigateway_console).\n\nSimply create a `{proxy+}` route that uses the `ANY` method and all requests will be routed to your Lambda function and processed by the `lambda-api` module. In order for a \"root\" path mapping to work, you also need to create an `ANY` route for `/`.\n\n## Reusing Persistent Connections\n\nIf you are using persistent connections in your function routes (such as AWS RDS or Elasticache), be sure to set `context.callbackWaitsForEmptyEventLoop = false;` in your main handler. This will allow the freezing of connections and will prevent Lambda from hanging on open connections. See [here](https://www.jeremydaly.com/reuse-database-connections-aws-lambda/) for more information.\n\n## TypeScript Support\n\nAn `index.d.ts` declaration file has been included for use with your TypeScript projects (thanks @hassankhan). Please feel free to make suggestions and contributions to keep this up-to-date with future releases.\n\n**TypeScript Example**\n\n```typescript\n// import AWS Lambda types\nimport { APIGatewayEvent, Context } from 'aws-lambda';\n// import Lambda API default function\nimport createAPI from 'lambda-api';\n\n// instantiate framework\nconst api = createAPI();\n\n// Define a route\napi.get('/status', async (req, res) =\u003e {\n  return { status: 'ok' };\n});\n\n// Declare your Lambda handler\nexports.run = async (event: APIGatewayEvent, context: Context) =\u003e {\n  // Run the request\n  return await api.run(event, context);\n};\n```\n\n## Contributions\n\nContributions, ideas and bug reports are welcome and greatly appreciated. Please add [issues](https://github.com/jeremydaly/lambda-api/issues) for suggestions and bug reports or create a pull request.\n\n## Are you using Lambda API?\n\nIf you're using Lambda API and finding it useful, hit me up on [Twitter](https://twitter.com/jeremy_daly) or email me at contact[at]jeremydaly.com. I'd love to hear your stories, ideas, and even your complaints!\n","funding_links":[],"categories":["JavaScript","Frameworks","Open Source Repos"],"sub_categories":["Lambda"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeremydaly%2Flambda-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjeremydaly%2Flambda-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeremydaly%2Flambda-api/lists"}