Gatsby Functions help you build Express-like backends without running servers.
Functions are generally available in sites running Gatsby 3.7 and above.
src/api/* are mapped to function routes like files in
src/pages/* become pages. So
src/api is a reserved directory for Gatsby.
For example, the following Function is run when you visit the URL
A Function file must export a single function that takes two parameters:
req: Node’s http request object with some automatically parsed data
res: Node’s http response object with some extra helper functions
Query strings and common body content types are automatically parsed and available at
Read more about supported data formats.
Sometimes you want to respond differently to GETs vs. POSTs or only respond to one method.
Only HTTP headers prefixed with
x-gatsby- are passed into your functions.
Site environment variables are used to pass secrets and environment-specific configuration to Functions.
Forms and Functions are often used together. For a working example you can play with locally, see the form example. The Forms doc page is a gentle introduction for building forms in React. Below is sample code for a very simple form that submits to a function that you can use as a basis for building out forms in Gatsby.
Plugins and themes can ship functions! This is powerful as it lets you pair frontend code with backend code. For example, if you built a plugin for an authorization service that includes a login component, you could ship alongside the component, a serverless function the component can use to connect to the remote API.
Plugin/theme functions work exactly the same as normal functions except their routes must be created under the plugin’s namespace e.g.
Shadowing with functions works similar to how shadowing works in general. You can shadow a plugin/theme function by copying the file from the plugin/theme’s
src tree into your site’s
src tree. For example, to shadow the
/gatsby-plugin-cool/do-something function from the
gatsby-plugin-cool plugin, you’d copy
src/api/gatsby-plugin-cool/do-something.js. From there, you can overwrite the implementation of the
/do-something function as you normally would.
- Gatsby Functions do not support dynamic routes in Gatsby Cloud at the moment
- Bundling in native dependencies is not supported at the moment