Netlify offers the ability for sites to deploy and call serverless functions via Netlify Functions. To begin using Netlify Functions with Gatsby Cloud, first login to your Netlify dashboard and configure your site to use Functions.
Once that's completed, you will need to make sure your build on Gatsby Cloud moves necessary files to the functions folder you specified on Netlify. This tutorial assumes your are using the default /functions
directory.
How to Deploy Your Functions
If your functions don't have any dependencies, you can simply place them in the /static/functions
directory at the root of the Gatsby site. The build process will automatically copy the functions to /public/functions
and deploy them with the built site.
If your functions have dependencies on other modules, see the next section.
How to Build Your Functions
Under the hood, Gatsby Cloud uses @netlify/zip-it-and-ship-it
to deploy your functions, which does not build, transpile, or install the function dependencies; this needs to be done before deployment.
There are two approaches you can use to build functions that require dependencies.
Option 1: onPostBuild
script with package manager
- Add your functions to
/static/functions
- Add a
package.json
specifying the dependencies to/static/functions
- Add an
onPostBuild
script togatsby-node.js
that installs your function dependencies
//gatsby-node.js
const util = require("util");
const child_process = require("child_process");
const exec = util.promisify(child_process.exec);
exports.onPostBuild = async (gatsbyNodeHelpers) => {
const { reporter } = gatsbyNodeHelpers;
const reportOut = (report) => {
const { stderr, stdout } = report;
if (stderr) reporter.error(stderr);
if (stdout) reporter.info(stdout);
};
// NOTE: the gatsby build process automatically copies /static/functions to /public/functions
reportOut(await exec("cd ./public/functions && npm install"));
};
Option 2: onPostBuild
script with netlify-lambda
- Install
netlify-lambda
as a project dev dependency
npm install netlify-lambda --save-dev
- Add a script to your project
package.json
to runnetlify-lambda build
{
"scripts": { "lambda": "netlify-lambda build <your functions folder>" }
}
- Add a
netlify.toml
file to your project with the followingfunctions
configuration
[build]
functions="public/functions"
//gatsby-node.js
const util = require("util");
const child_process = require("child_process");
const exec = util.promisify(child_process.exec);
exports.onPostBuild = async (gatsbyNodeHelpers) => {
const { reporter } = gatsbyNodeHelpers;
const reportOut = (report) => {
const { stderr, stdout } = report;
if (stderr) reporter.error(stderr);
if (stdout) reporter.info(stdout);
};
reportOut(await exec("npm run lambda"));
};