DEV Community

Karin for Netlify

Posted on • Originally published at developers.netlify.com

Netlify integrations can now inject serverless functions to enhance any site. Here’s how

It’s long been possible to use Netlify Functions in your site. But with the Netlify SDK we’re bringing the power of function injection to integration builders as well. This allows you to build one integration that can power any of your Netlify sites using Netlify Functions with the click of a button! This guide will show you three different types of functions you can inject into a site.

TL;DR

This guide explains the three different types of functions that you can inject into a site using a Netlify integration: serverless functions, scheduled functions and background functions (only available for sites that are on Core Pro and Core Enterprise plans). We'll make an integration by using the functions boilerplate from the Netlify CLI, and deploy it for use in an example site.

You can explore the full source code with examples to see how to inject each of these three types of functions. Or you can add this integration to your Netlify account by clicking the button below.

You can explore the full source code of this integration to see how we built this integration. Or add the integration to your Netlify account by clicking the button below.

Deploy to Netlify

Prerequisites

Let’s get started

First, run npm create @netlify/sdk@latest to create a new integration. Answer the prompts following the steps below.

? Where do you want to create the integration? sdk-sf-injection-integration
? What is the slug of the integration? (e.g. my-integration) sdk-sf-injection-integration
? Summarize what your integration does. This will be shown on the integration's card on the Integrations page. It has some examples for
injecting functions
? Which boilerplate should be included? Functions Injection (beta)
? What level will this integration be installed on? site (recommended for Build Event Handlers, Edge Functions and Functions)
? Which package manager do you want to use? pnpm
? Do you want to create or link a Netlify site to your integration? This will help you test your integration and will be used to host
your integration. skip
Enter fullscreen mode Exit fullscreen mode

This will create your integration in the folder with the name you provided! It will have a scaffold that the SDK created for you. There is a basic structure there that looks like this:

├── integration.yaml
├── netlify.toml
├── node_modules
├── package-lock.json
├── package.json
├── src
│ ├── index.ts
│ └── functions
│   └── hello-world.mts
└── tsconfig.json
Enter fullscreen mode Exit fullscreen mode
  • integration.yaml - The integration configuration file. This is where you configure the integration name, description, and other metadata.
  • netlify.toml - The Netlify configuration file. This is where you configure the settings for your integration.
  • src/index.ts - The entry point for developing the integration.
  • src/functions/ - The folder to store your functions in.
  • src/functions/hello-world.mts - An example function.

Deploy the integration

You have a working integration now! Follow this guide to deploy your integration to your Netlify account so we can try it out on a Netlify site.

After following that guide, let’s try it out on one of your Netlify sites! You can test it out by finding a site in your Netlify account (make a simple test site if necessary). When you’re in the dashboard of that site, select ‘integrations’ in the site’s sidebar. Then, find your integration in the list of private integrations. The last step is to click ‘enable’ on the integration card.

Enable your integration by selecting 'enable' on the integration card in the Netlify UI

Test it out by redeploying your test site and visiting your site on the /.netlify/functions/sf_prefix_hello-world path. It should say Hello, world!.

Check out the integration code

Open up the src/index.ts file in your editor to see how the integration is set up. In that file you’ll see the following:

Test it out by redeploying your test site and visiting your site on the /.netlify/functions/sf_prefix_hello-world path. It should say Hello, world!.

Check out the integration code

Open up the src/index.ts file in your editor to see how the integration is set up. In that file you’ll see the following:

// src/index.ts
import { NetlifyIntegration } from "@netlify/sdk";

const integration = new NetlifyIntegration();

integration.addFunctions("./src/functions", {
  prefix: "my_unique_prefix",
});

export { integration };
Enter fullscreen mode Exit fullscreen mode

The addFunctions method defines where the SDK can find your function. In this case it’s ./src/functions. It also provides a prefix for your functions. This is important because it helps avoid naming conflicts with functions that might be injected by other integrations or frameworks.

Different function options

Let’s dive into the different types of functions you can inject through the SDK: serverless functions, background functions and scheduled functions.

Serverless function

The first type is the one that is already part of the scaffold that the SDK created for you, a default serverless function.

What can you use a serverless function for?

These types of functions can be used for a lot of different usecases, some examples are fetching live data from an API, returning dynamic images, sending automated emails or validating user input.

How do you create a serverless function?

If we open the file src/functions/hello-world.mts in the integration’s repository we’ll see the following:

// Documentation: https://sdk.netlify.com

export default async () => {
  return new Response("Hello, world!");
};
Enter fullscreen mode Exit fullscreen mode

You’re looking at the most basic version of a function. As mentioned before, this function can be found on the /.netlify/functions/my_unique_prefix_hello-world endpoint on sites where it is installed. You can change this path by adding a config to the file like this:

// Documentation: https://sdk.netlify.com

export default async () => {
  return new Response("Hello, world!");
};

export const config = {
  path: "/test",
};
Enter fullscreen mode Exit fullscreen mode

How do you use a serverless function?

If you were to commit this change to your integration and push it with continuous deployment set up, it will automatically deploy the changes to your integration. When you try it out on your test site by redeploying your site, this function should be accessible through the /test endpoint.

Background function

Background functions can only be used on sites in teams that are on Core Pro or Core Enterprise plans, so keep this in mind if you’re planning on building that kind of integration.

What can you use a background function for?

A background function is useful if your integration needs to inject a function that has to run for longer than the 10 second maximum execution time permitted for regular serverless functions. A background function can run for up to 15 minutes and doesn’t need to complete before a visitor can take next steps on the site it is injected in. It can be used for tasks such as batch processing, scraping or for slower API workflow execution.

As mentioned in the background functions documentation, background functions are invoked asynchronously. They return an initial 202 success response and will then run in the background until it completes.

How do you create a background function?

Creating a background function works similar to normal functions, the only difference is that you append the name of the file with -background. Let’s create one!

First, let’s install a useful dependency with npm install @netlify/functions. Then, in your src/functions directory create a file called count-background.mts, add the following content:

import type { BackgroundHandler, HandlerEvent, HandlerContext } from "@netlify/functions";

export const handler: BackgroundHandler = (event: HandlerEvent, context: HandlerContext) => {
  const sleep = (ms: number) => {
    return new Promise((resolve) => setTimeout(resolve, ms));
  };

  (async () => {
    for (let i = 0; i <= 60; i++) {
      const date = new Date();
      await sleep(1000);
      console.log(date.toLocaleString(), i);
    }
    console.log("Done");
  })();
};

export const config = {
  path: "/count",
};
Enter fullscreen mode Exit fullscreen mode

How do you use a background function?

This deploys to an endpoint at /count relative to the base URL of the site your integration is used on. When this function is invoked, the function returns an initial 202 success response. It will then log numbers 1 through 60. Try it out by committing it to your integration’s repository and pushing your changes. Your integration will redeploy, after this make sure to also redeploy your test site and call this new function.

Scheduled function

Scheduled functions are an exciting feature that makes it possible to run functions on a regular and consistent schedule, kind of like a cron job!

What can you use a scheduled function for?

Scheduled functions provide so many different possibilities! From invoke a set of APIs to collate data for a report at the end of every week to backing up data from one data store to another at the end of every night or building and/or deploying all your static content every hour instead of for every authored or merged pull request.

How do you create a scheduled function?

Creating a scheduled function works similar to normal functions, the only difference is that you export a config object from the file that defines when the function should run with something called a “cron expression”.

Create a new file in your src/functions directory called hourly-run.mts and add the following content:

import type { Config } from "@netlify/functions";

export default async (req: Request) => {
  const { next_run } = await req.json();

  console.log("Received event! Next invocation at:", next_run);

  return new Response("OK");
};

export const config: Config = {
  schedule: "* * * * *",
};
Enter fullscreen mode Exit fullscreen mode

How do you use the scheduled function?

Commit it to your integration’s repository and push your changes. Your integration will redeploy, after this make sure to also redeploy your test site and call this new function. By going to your function logs you should be able to see an hourly message.

What’s next?

Go ahead and use all of these new possibilities to build something that your team can really use with a private integration! Create one integration and apply it to your different Netlify sites to automate your workflows. Happy coding!

More information

Top comments (0)