Tutorial - Customize tokens using workflows
Workflows
You can fetch third party data from your workflows and use within them.
Add the following code to your Workflow.ts file:
import { onUserTokenGeneratedEvent, accessTokenCustomClaims, WorkflowSettings, WorkflowTrigger, fetch,} from "@kinde/infrastructure";
export const workflowSettings: WorkflowSettings = { id: "addThirdPartyDataToAccessToken", name: "Add third party data to access token", trigger: WorkflowTrigger.UserTokenGeneration, bindings: { "kinde.accessToken": {}, "kinde.fetch": {}, url: {}, },};
export default async function FetchThirdPartyDataWorkflow( event: onUserTokenGeneratedEvent) { const accessToken = accessTokenCustomClaims<{ lifetime_subscriber: boolean; }>();
const loggedInUserId = event.context.user.id; const { data: userData } = await fetch(`https://my-website.com/api/user/${loggedInUserId}`, { method: "GET", responseFormat: "json", headers: { "Content-Type": "application/json", }, });
accessToken.lifetime_subscriber = userData.lifetime_subscriber || false;}The code fetches the user data from the third party data source and stores it in the access token. GET is appropriate for a read-only lookup by user ID, matching the kinde.fetch examples. If you need to send sensitive data in the request body, use POST and consider kinde.secureFetch instead.
Required bindings:
kinde.fetch: to fetch the third party dataurl: required for Kinde to use fetch under the hoodkinde.accessToken: to update the the access tokenRead more about the kinde.fetch binding.
Go to Kinde > Settings > Data management > Env variables and add any environment variables you need to use in your workflow. (e.g., API_URL, API_KEY, etc.)
Add the following sample code to your Workflow.ts file:
import { onUserTokenGeneratedEvent, accessTokenCustomClaims, WorkflowSettings, WorkflowTrigger, fetch, getEnvironmentVariable,} from "@kinde/infrastructure";
export const workflowSettings: WorkflowSettings = { id: "addThirdPartyDataUsingEnvs", name: "Add third party data to access token using environment variables", trigger: WorkflowTrigger.UserTokenGeneration, bindings: { "kinde.accessToken": {}, "kinde.fetch": {}, "kinde.env": {}, url: {}, },};
export default async function FetchThirdPartyDataWorkflow( event: onUserTokenGeneratedEvent) { const accessToken = accessTokenCustomClaims<{ lifetime_subscriber: boolean; }>();
const apiKey = getEnvironmentVariable("API_KEY")?.value; if (!apiKey) { console.error("API_KEY environment variable is not set"); return; }
const loggedInUserId = event.context.user.id; const { data: userData } = await fetch(`https://my-website.com/api/user/${loggedInUserId}`, { method: "GET", responseFormat: "json", headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json", }, });
accessToken.lifetime_subscriber = userData.lifetime_subscriber || false;}Required additional binding:
kinde.env: to access the environment variablesRead more about the environment variables and secrets.