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 withnpx 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
.
export async function handler({context, event}) {
const URL = process.env.DEPLOY_HOOK_URL
if (!URL) {
throw new Error("DEPLOY_HOOK_URL is not set")
}
try {
await fetch(URL)
} catch (error) {
console.error(error)
}
}
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
The GROQ filter in this example is important. It makes sure that the function only runs when the language is set to English. When we generate a new translation in the next code block, Translate sets that field to Greek. This stops the new document from triggering the same function and creating a recursive loop.
You could also create draft or version documents to prevent the "on publish" function from triggering.
For this approach, we have documents with a language
set. We only want the English language files.
- Import and configure the
@sanity/client
. - Capture the document
data
from theevent
. - Construct a
translate
request.
import { createClient } from '@sanity/client'
export async function handler({context, event}) {
const { data } = event
const client = createClient({
...context.clientOptions,
apiVersion: 'vX',
})
const targetLanguage = {
id: "el-GR",
title: "Greek"
}
// Create a consistent ID based on the source and target language.
// This allows the function to override the document in the future
const targetId = `${data._id}-${targetLanguage.id}`
try {
await client.agent.action.translate({
// Replace with your schema ID
schemaId: "sanity.workspace.schema.default",
// Tell the client to run the action asynchronously.
// We don't need to wait for it to complete.
async: true,
// Tell the client the ID of the document to use as the source.
documentId: data._id,
// Set the language field to the target language.
languageFieldPath: "language",
// Set the operation mode
// createOrReplace will override the ID in future invocations.
targetDocument: {
operation: "createOrReplace",
_id: targetId
},
// Set the 'from' and 'to' language
fromLanguage: {id: "en-US", title: "English"},
toLanguage: {id: targetLanguage.id, title: targetLanguage.title},
});
} catch (error) {
console.error(error)
}
}
Now, when you publish an English-language document, it will create a Greek version. Learn more about Agent Actions here.
Was this page helpful?