This how-to guide will demonstrate how to ship your serverless functions to Netlify with your Gatsby Cloud site.
How to Deploy Your Functions
First, login to your Netlify account and configure your site to use Functions. Next, you will need to make sure your build on Gatsby Cloud moves necessary files to the functions folder you specified on Netlify. This guide assumes you are using the default functions directory, /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
// If you use yarn, replace "npm install" with "yarn install"
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 " }
}
- 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"));
};
Comments
0 comments
Please sign in to leave a comment.