Compute and AI

Functions cheat sheet

Common patterns and techniques for creating Functions.

Functions create the ability for countless content-driven opportunities. This guide collects common patterns and approaches to working with Functions.

Prerequisites:

  • Complete the Functions quick start, or be comfortable writing and deploying a Sanity Function.
  • sanity CLI v3.88.1 or higher is required to interact with Blueprints and Functions. You can always run the latest CLI commands with npx sanity@latest.

The examples below assume you've created a new function, and configured it to trigger based on your own schema requirements.

Ping an endpoint on publish

A common approach to invalidating CDNs and triggering new builds is to ping, or make a GET request, to an endpoint. Some require you to provide specifics, such as the endpoint or slug for targeted refreshes. Others only require a single URL.

Create a function and configure it to trigger when your target document publishes. For the example, make sure to define an environment variable named DEPLOY_HOOK_URL.

To find the deploy or trigger URL for your provider, check their documentation. We've included a few common links below:

Automatically translate documents

You can combine Translate with Functions to translate documents automatically.

We recommend completing the quick start if you haven't used Translate before.

First, create a function and configure it to only trigger when a document's language is in your "from" language. Here's an example of the function resource in blueprints.json.

{
  "displayName": "translate",
  "name": "translate",
  "src": "functions/translate",
  "type": "sanity.function.document",
  "event": {
    "on": [
      "publish"
    ],
    "filter": "_type == 'post' && language == 'en-US'",
    "projection": "_id"
  }
}

Use caution when creating documents

For this approach, we have documents with a language set. We only want the English language files.

Now, when you publish an English-language document, it will create a Greek version. Learn more about Agent Actions here.

Was this page helpful?

Functions cheat sheet | Sanity Docs