Handling intermittent connectivity in Web SDK - adobe/alloy GitHub Wiki
You can handle intermittent connectivity in Web SDK by catching sendEvent failures and queueing them for later. This code can be used to queue events that fail for later. The RETRY_INTERVAL
in the code can be changed to the interval that you would like to use.
const queuedEvents = [];
const RETRY_INTERVAL = 5000; // 5 seconds
const trySendingQueuedFailures = () => {
if (queuedEvents.length > 0) {
console.log("Attempting to send queued event.", queuedEvent[0]);
alloy("sendEvent", queuedEvents[0])
.then(() => {
queuedEvents.shift();
trySendingQueuedFailures();
})
.catch(() => {
console.log("Queued event failed. Re-queueing", queuedEvent[0]);
setTimeout(trySendingQueuedFailures, RETRY_INTERVAL);
});
}
};
// use this instead of alloy("sendEvent", options);
const sendEventWithQueuedFailures = (options) => {
const actualTimestamp = new Date().toISOString();
if (queuedEvents.length > 0) {
console.log("There are already queued events, so this event will be sent after those succeed.", options);
queuedEvents.push({...options, data: { ...(options.data || {}), actualTimestamp }});
} else {
alloy("sendEvent", options).catch(() => {
console.log("Event failed to send. Queueing...", options);
queuedEvents.push({...options, data: { ...(options.data || {}), actualTimestamp }});
setTimeout(trySendingQueuedFailures, RETRY_INTERVAL);
});
}
};
You'll notice the code above is saving the actualTimestamp as part of the data payload when events are queued. This is so that we can record the timestamp when the event occurred and not when it was successfully sent. To make this work, you'll also need to add this code to your onBeforeEventSend so that the actualTimestamp is used for the event.
if (content.data?.actualTimestamp) {
content.xdm.timestamp = content.data.actualTimestamp;
delete content.data.actualTimestamp;
}