Skip to content

Instantly share code, notes, and snippets.

@jensen
Created February 20, 2023 02:10
Show Gist options
  • Save jensen/1d80ed0d31649a1dd60049621cfd3c58 to your computer and use it in GitHub Desktop.
Save jensen/1d80ed0d31649a1dd60049621cfd3c58 to your computer and use it in GitHub Desktop.
Adding profiles with Klaviyo API
const BASE_URL = "https://a.klaviyo.com/api";
const baseHeaders = new Headers({
accept: "application/json",
revision: "2023-01-24",
Authorization: `Klaviyo-API-Key ${process.env.KLAVIYO_API_KEY}`,
});
const getHeaders = new Headers(baseHeaders);
const postHeaders = new Headers(baseHeaders);
postHeaders.append("Content-Type", "application/json");
export const subscribeUserWithEmail = async (
user: Omit<User, "plan" | "name"> & { description: string }
) => {
const profiles = await fetch(
`${BASE_URL}/profiles?filter=equals(email,"${user.email}")`,
{
method: "GET",
headers: getHeaders,
}
).then((response) => response.json());
if (profiles.data.length === 0) {
const profile = await fetch(`${BASE_URL}/profiles`, {
method: "POST",
headers: postHeaders,
body: JSON.stringify({
data: {
type: "profile",
attributes: {
email: user.email,
external_id: user.id,
first_name: user.first_name,
last_name: user.last_name,
properties: {
"Which best describes you?": user.description,
},
},
},
}),
}).then((response) => response.json());
console.log(profile);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment