Hey there, fellow JavaScript devs! Ready to dive into the world of Klaviyo API integration? Let's get our hands dirty with some data syncing goodness for user-facing integrations. Buckle up!
First things first, let's get you set up with Klaviyo. You'll need an API key, which you can grab from your Klaviyo account settings. Keep it safe – it's your golden ticket!
Here's how you might set up a basic request:
const axios = require('axios'); const klaviyoApi = axios.create({ baseURL: 'https://a.klaviyo.com/api', headers: { 'Authorization': 'Klaviyo-API-Key your-api-key-here' } });
Now that we're all set up, let's fetch some data! Klaviyo's got a ton of endpoints for profiles, lists, campaigns – you name it. Here's a quick example of fetching user profiles:
async function getProfiles() { try { const response = await klaviyoApi.get('/v2/people'); return response.data; } catch (error) { console.error('Error fetching profiles:', error); } }
Writing data is just as easy. Let's update a profile and track an event:
async function updateProfileAndTrackEvent(profileId, eventName) { try { // Update profile await klaviyoApi.put(`/v2/person/${profileId}`, { properties: { last_updated: new Date().toISOString() } }); // Track event await klaviyoApi.post('/v2/track', { event: eventName, customer_properties: { $id: profileId }, properties: { timestamp: new Date().toISOString() } }); console.log('Profile updated and event tracked successfully!'); } catch (error) { console.error('Error:', error); } }
Real-time syncing? Webhooks to the rescue! Set them up in your Klaviyo account, then handle them like this:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { event, data } = req.body; switch(event) { case 'profile_updated': // Handle profile update break; case 'list_subscribed': // Handle new subscription break; // Add more cases as needed } res.sendStatus(200); });
Two-way sync can be tricky, but here's a simple approach:
async function twoWaySync(localData, klaviyoData) { const merged = {}; for (const key in localData) { merged[key] = localData[key].timestamp > klaviyoData[key].timestamp ? localData[key].value : klaviyoData[key].value; } // Update both local and Klaviyo data with merged data await updateLocalData(merged); await updateKlaviyoProfile(merged); }
Don't let errors catch you off guard! And remember, Klaviyo has rate limits. Here's how to handle both:
async function makeApiCall(endpoint, method = 'get', data = null) { const maxRetries = 3; let retries = 0; while (retries < maxRetries) { try { const response = await klaviyoApi[method](endpoint, data); return response.data; } catch (error) { if (error.response && error.response.status === 429) { // Rate limited, wait and retry const waitTime = parseInt(error.response.headers['retry-after']) * 1000; await new Promise(resolve => setTimeout(resolve, waitTime)); retries++; } else { throw error; } } } throw new Error('Max retries reached'); }
Want to speed things up? Batch operations are your friend:
async function batchProfileUpdate(profiles) { const batchSize = 100; for (let i = 0; i < profiles.length; i += batchSize) { const batch = profiles.slice(i, i + batchSize); await klaviyoApi.post('/v2/people/batch', { profiles: batch }); } }
Always test in Klaviyo's sandbox environment before going live. Here's a simple test setup:
const chai = require('chai'); const expect = chai.expect; describe('Klaviyo API Integration', () => { it('should fetch profiles successfully', async () => { const profiles = await getProfiles(); expect(profiles).to.be.an('array'); expect(profiles.length).to.be.greaterThan(0); }); // Add more tests as needed });
And there you have it! You're now armed with the knowledge to read and write data like a pro using the Klaviyo API. Remember to keep your code clean, handle errors gracefully, and always respect those rate limits. Happy coding, and may your data always be in sync!