Middleware and Helpers
Gatsby Functions provides an Express-like architecture that simplifies building Node.js APIs. We include a number of middlewares to parse common request data as well as response helpers.
We parse commonly used data types. You can parse more by adding custom middleware. Data available by default on the
- Cookies at
- URL Queries (e.g.
- Form parameters and data at
- JSON POST bodies at
- Files uploaded from forms at
res.send(body)— returns the response. The
bodycan be a
res.json(body)— returns a JSON response. The
bodycan be any value that can be serialized with
res.status(statusCode)— set the HTTP status for the response. Defaults to
res.redirect([statusCode], url)— Returns a redirect to a URL. Optionally set the statusCode which defaults to
Custom Connect/Express middleware are supported.
An example of how to add CORS support to a Function:
Support for overriding default config added in
By default, Gatsby is using following configuration defaults to parse request body and make it available as
req.body field in appropriate format:
Those settings work in most cases, but sometimes you might need to adjust them to cover your use case. Gatsby allows exporting an object named
config from your function handler module. This object allows you to control the
body-parser middleware used by Gatsby Functions. Gatsby currently supports the
extended options for the
bodyParser configuration, which are documented by body-parser. The
limit property will allow configuration of payload size up to 32mb.
You can modify what
body-parser middleware can act on. Following configuration will force every request to use
raw parser and result in function handler receiving
req.body as a
Buffer. A setup like this is useful if you are looking to verify signature of webhooks (e.g. https://stripe.com/docs/webhooks/signatures).
By default, the limit is
100kb. If the request body is larger than that it will result in automatic
413 Request Entity Too Large response without executing function handler at all.
If your use case require a higher limit, you can bump it up in
You can import
gatsby to type your
When using the
config and changing the
type on one of the body parser middlewares, it’s important to realize that all body parser middlewares are still being applied with this specific order:
Here’s a concrete example:
If you want
json to be used for all possible requests for a given function, it won’t be enough to just set
type: "*/*" for the
json middleware. You also need to change the
type for middlewares that are higher in priority, so they don’t accidentally match and handle request before the
json middleware can process it: