Skip to content

Call API Handlers from Build Event Handlers

It’s possible to call an API handler from a build event handler. This is useful if you want to interact with the Integration API or Netlify API from a build event handler.

There are a few steps involved in this:

  1. Generate a build token
  2. Create a Build Context
  3. Use the Build Context in a build event handler

Generate a build token

In order for your build event handler to call an API handler, you need to generate a build token. This can be done by customizing the enablement flow or by creating a separate API handler that’s called from an Integration UI component.

The following example shows how to generate a build token inside an API handler that is called on the site level from an Integration UI component:

src/index.ts
import { NetlifyIntegration } from "@netlify/sdk";
const integration = new NetlifyIntegration();
integration.addApiHandler("create-token", async (event, context) => {
const { client, siteId } = context;
try {
// This generates a build token for the site with the given siteId
const { token } = await client.generateBuildToken(siteId, accountId);
// This sets the build token for the site with the given siteId
await client.setBuildToken(accountId, siteId, token);
return {
statusCode: 200,
body: JSON.stringify({
message: "Successfully set build token",
}),
};
} catch (error) {
console.error(error);
throw new Error("Error setting build token");
}
});

Create a Build Context

Once you’ve generated a build token, you’re ready to set up a Build Context. This creates a context object that you can access on any build event handler. This is a necessary step to pass data from an API handler to a build event handler.

Inside the file src/index.ts, where you have defined your Netlify integration and your API handlers, add the following code:

src/index.ts
import { NetlifyIntegration } from "@netlify/sdk";
const integration = new NetlifyIntegration();
integration.addBuildEventContext(async ({ client }) => {
// add any logic to retrieve the data you need from either the Integration API or the Netlify API using `client`.
// then return that data as an object
return {
useful_data: "1234",
};
});

Use the Build Context in a build event handler

Now that you have passed along data from your API handler to your build event handler, you can access the data from within your build event handler. The following example shows how to access the useful_data from the Build Context:

src/index.ts
import { NetlifyIntegration } from "@netlify/sdk";
const integration = new NetlifyIntegration();
integration.addBuildEventHandler("onPreBuild", ({ buildContext }) => {
console.log(buildContext.useful_data);
});