We are going to design a resiliency story for third-party widgets.
The goal is to handle failures gracefully, including timeouts, sandboxing (security/isolation), and providing a fallback UI when the widget fails to load or function.
Components:
Timeout: We don't want the widget to hang indefinitely. We'll set a timeout for the widget to load and become interactive.
Sandboxing: The third-party widget runs in an isolated environment (like an iframe) to prevent security issues and to contain any bugs or heavy resource usage.
Fallback UI: If the widget fails to load (due to timeout, network error, or widget error) we show a fallback UI that might include:
A static message or image.
A button to reload the widget.
Optionally, logging the error for monitoring.
Steps:
We'll create a wrapper component that will manage the state of the widget (loading, success, failed, timeout).
We'll use an iframe to sandbox the widget. The iframe will have a sandbox attribute to restrict its capabilities (we can adjust as needed).
We'll set a timer for the widget to load. If the widget doesn't signal that it's ready within the timeout, we'll trigger the fallback.
We'll use postMessage to communicate with the iframe. The widget inside the iframe should send a message to the parent when it's ready, or if it encounters an error.
However, note that we are not in control of the third-party widget's code. So we have to rely on the fact that the widget provides a way to communicate (like a callback) or we have to detect failure via the iframe's onerror and onload events.
But note: not all third-party widgets are designed to communicate via postMessage. So we might have to rely on the iframe's load event and then check the content of the iframe? That might be same-origin issue.
Alternatively, we can design our wrapper to work with two scenarios:
Scenario 1: The widget supports postMessage.
We set a timeout and wait for a "ready" message from the iframe.
If we get the message, we clear the timeout and mark as success.
If timeout occurs, we mark as timeout and show fallback.
Scenario 2: The widget does not support postMessage.
We rely on the iframe's onload event. But note: onload fires when the iframe finishes loading, which might be even if the widget inside has an error? Not necessarily.
We can set a timeout from the moment we set the iframe src. If the iframe's onload doesn't fire within the timeout, we mark as timeout.
But what if the iframe loads but the widget inside is broken? We might not know.
However, if we are using an iframe and the third-party widget is from a different origin, we cannot inspect the iframe's content due to same-origin policy. So we cannot know if the widget inside has thrown an error.
Therefore, we must rely on the third-party widget to communicate with us (via postMessage) or we only rely on the iframe load event and assume that if the iframe loads, the widget is working.
But this is not resilient enough. We need a way to detect if the widget is functional.
Alternative approach:
We can design a handshake:
Parent sets the iframe src with a special query parameter that indicates we want a handshake (if the widget supports it).
Widget, if it supports, sends a "handshake" message to the parent.
Parent waits for the handshake. If received, then widget is ready. If not within timeout, then we assume the widget doesn't support handshake? But then what? We can't know if it's broken.
Given the constraints, we might have to accept that for widgets that don't support our handshake protocol, we only have the iframe's load event and a timeout.
But note: the iframe's load event fires when the iframe's document is loaded, not necessarily when the widget is ready. And if the widget has JavaScript that runs asynchronously, we might get a false positive.
So, we design two modes:
Mode A: With handshake (postMessage) support.
Mode B: Without handshake.
For Mode A, we wait for the handshake message. For Mode B, we wait for the iframe load event and then set a timer for the widget to become interactive? But we can't know.
Actually, without handshake we are limited. We might have to rely on the third-party widget to provide a callback that we can set? But if it's a third-party widget, we might not have that.
Given the complexity, let's assume we are building a system that can work with both:
We will set a timeout from the moment we start loading the widget (say 5 seconds).
We will listen for the iframe's load event. When it loads, we start a timer (say 2 seconds) to see if the widget sends a handshake. If it does, we clear the timeout and the success state. If not, we wait until the overall timeout (5 seconds) and then mark as timeout.
But note: the iframe load event might fire after 4 seconds, then we wait 2 more seconds for handshake, but the overall timeout is 5 seconds. So if the handshake comes at 4.5 seconds, we are good. If not, at 5 seconds we mark timeout.
However, what if the iframe load event never fires? Then the overall timeout will trigger.
Steps:
code
let timeoutId;
let loadEventFired = false;
let handshakeReceived = false;
const startTimer = () => {
timeoutId = setTimeout(() => {
if (!handshakeReceived) {
// We have a timeout, either the iframe didn't load or the handshake didn't come.
setState('failed');
}
}, 5000);
};
const iframe = document.createElement('iframe');
iframe.onload = () => {
loadEventFired = true;
// We wait for handshake for up to 2 more seconds? But the overall timeout is 5 seconds.
// Actually, we started the timer already. So if the handshake comes after load but before 5 seconds, we clear the timer.
};
window.addEventListener('message', (event) => {
// Check if the message is from our iframe and is the handshake.
if (event.source === iframe.contentWindow && event.data === 'widget-ready') {
handshakeReceived = true;
clearTimeout(timeoutId);
setState('success');
}
});
iframe.src = widgetUrl + (widgetUrl.includes('?') ? '&' : '?') + 'handshake=1';
document.body.appendChild(iframe);
startTimer();
But note: the iframe's onload might fire before the handshake? Yes, because the iframe loads the HTML, then the widget's JavaScript runs and sends the handshake.
However, if the widget doesn't support handshake, we will wait until the timeout and then mark as failed.
This is not perfect because if the widget loads but doesn't send handshake (because it doesn't support) and then we show fallback even though the widget might be working.
We could have a configuration for each widget:
If the widget is known to support handshake, we wait for handshake.
If not, we rely on iframe load and then assume it's working? But then if it loads but is broken (like a JS error) we won't know.
Alternatively, we can have a heartbeat: the widget sends a heartbeat every few seconds? But again, that requires the widget to support.
Given the constraints, we might have to accept that without the widget's cooperation we cannot guarantee detection of a broken widget that has loaded.
So, our plan:
We'll have a wrapper that:
Creates an iframe with sandbox attributes (we'll set a restrictive sandbox but allow scripts and same-origin? Actually, for third-party we want to isolate, so we might not allow same-origin. But then we cannot use postMessage? Actually, postMessage works across origins.
Let's set the iframe sandbox to: "allow-scripts allow-same-origin" if we want the widget to run scripts and be able to postMessage? But note: allow-same-origin will treat the iframe as same origin as the parent? No, it will treat the iframe's content as its own origin. But if the iframe is from a different domain, then it's not same-origin. The sandbox attribute without 'allow-same-origin' will keep the iframe in a unique origin. We want that for security? But then the iframe cannot access the parent's DOM and the parent cannot access the iframe's DOM. However, postMessage works regardless.
So we can use:
code
sandbox="allow-scripts"
This allows the iframe to run scripts but keeps it in a unique origin. Then the widget can postMessage to the parent, and the parent can postMessage to the iframe.
But note: if we don't allow same-origin, then the iframe's content is treated as being from a unique origin, and the parent cannot access iframe.contentWindow.document (which we don't need). And the iframe cannot access the parent's DOM.
So we are safe.
We set a timeout for the entire process (loading + handshake). We'll make it configurable.
We listen for the iframe's load event. When it loads, we wait for the handshake (if the widget is supposed to send one). If the handshake comes, success. If the overall timeout fires first, we show fallback.
We also listen for error events on the iframe? The iframe's onerror might not fire for network errors? Actually, the iframe's onerror is not reliable for network errors. We might get an error event if the iframe fails to load? But it's not consistent.
We might also consider a reload button in the fallback UI to try again.
Implementation:
We'll create a React component (assuming React for this example) that:
code
- Takes props:
widgetUrl: string
handshakeMessage?: string (default: 'widget-ready') // the message we expect from the widget
timeout?: number (default: 5000)
fallback?: React.ReactNode (the fallback UI to show when failed or timeout)
onError?: (error: Error) => void (callback for errors)
- State: 'loading' | 'success' | 'failed'
- We'll use useEffect to set up the iframe and event listeners.
Steps in useEffect:
code
let isMounted = true;
const iframe = document.createElement('iframe');
iframe.style.display = 'block'; // or as needed
iframe.sandbox = 'allow-scripts'; // adjust as needed, maybe allow-forms? But we want to restrict.
// We'll set the src with a handshake parameter if needed? Actually, the widget might not look at query parameters.
// We can set a postMessage handshake without modifying the URL.
// But note: if the widget doesn't know to send a handshake, we cannot force it. So we rely on the widget to be built to send the handshake.
// Alternatively, we can inject a script into the iframe? But we cannot because of same-origin. Unless we use a proxy? That's too complex.
// So we assume the widget is built to send the handshake if it supports.
const handleMessage = (event) => {
// We should check event.origin? We might want to only accept messages from the expected origin? But we don't know the origin of the widget? It could be the widgetUrl's origin.
// We can check if event.origin is the same as the widgetUrl's origin? But the widgetUrl might be a relative path? We assume it's absolute.
// However, if we set the iframe src to a different domain, then event.origin should be that domain.
// But we might not want to restrict if the widget is from a CDN that has multiple domains? Then we might accept from any? That's less secure.
// We'll let the user of the component specify allowed origins? Or we can skip the check for simplicity in this example.
if (event.data === handshakeMessage) {
if (isMounted) {
clearTimeout(timeoutId);
setState('success');
window.removeEventListener('message', handleMessage);
}
}
};
window.addEventListener('message', handleMessage);
iframe.onload = () => {
// The iframe has loaded. We don't know if the widget inside is ready. We wait for the handshake.
// But we already started the timer.
};
// We might also want to listen for iframe's error? Not reliable.
// Append the iframe to a container (we need a ref to a container in the component)
const container = containerRef.current;
container.appendChild(iframe);
const timeoutId = setTimeout(() => {
if (isMounted) {
setState('failed');
window.removeEventListener('message', handleMessage);
// We might also want to remove the iframe? Or leave it? We can leave it and show fallback on top.
// Or we can remove the iframe and show fallback.
// Let's remove the iframe and show fallback to avoid broken widget using resources.
container.removeChild(iframe);
}
}, timeout);
return () => {
isMounted = false;
clearTimeout(timeoutId);
window.removeEventListener('message', handleMessage);
if (container.contains(iframe)) {
container.removeChild(iframe);
}
};
But note: if the handshake comes after the component unmounts, we don't want to set state. So we use isMounted.
However, the above has a race condition: the iframe might load and then the handshake might come after the timeout? Then we would set state on an unmounted component? We clear the timeout and remove the event listener on unmount, so it should be safe.
Also, if the handshake comes before the timeout, we clear the timeout and set success.
But what if the handshake never comes? Then the timeout fires and we set failed.
This works for widgets that support handshake.
For widgets that don't, we will always get a timeout and show fallback. That's not acceptable.
So we need a way to know if the widget supports handshake. We can have a prop supportsHandshake that the user sets. Then:
code
if (supportsHandshake) {
// wait for handshake, otherwise timeout.
} else {
// wait for iframe onload, then consider it success? But wait, what if the iframe loads but the widget is broken? We can't know.
// Alternatively, we can wait for iframe onload and then set a short timer (like 1 second) to see if the widget becomes interactive? But we can't know.
// Actually, without handshake, we have to assume that if the iframe loads, the widget is working. But that's not true if the widget has JS errors after load.
// We can try to detect errors by listening to iframe's error event? But that might not catch JS errors.
// Another idea: we can inject a script into the iframe that listens for errors and then sends a message? But we cannot because of same-origin.
// So without handshake, we are stuck with:
iframe.onload => setState('success') after a short delay? But then if the widget breaks after load, we won't know.
// Actually, the iframe's onload fires when the iframe's document is loaded. The widget's JavaScript might run and then throw an error. We cannot catch that.
// So without handshake, we can only do:
iframe.onload => setState('success')
// But then we have the timeout as a fallback in case the iframe never loads.
// So we adjust:
if (supportsHandshake) {
// wait for handshake, and we have a timeout for that.
} else {
// wait for iframe onload, and then set success immediately? We can set a short timeout after onload to see if handshake comes? But we already know it doesn't support.
// Actually, if it doesn't support handshake, we don't expect a handshake. So when iframe onload fires, we can set success.
// But then we have two different success conditions.
// Let's change:
We'll have two timers:
1. The overall timeout (for iframe to load and handshake to come, if applicable).
2. For non-handshake widgets, when iframe onload fires, we set success and clear the overall timeout.
So:
if (supportsHandshake) {
// We wait for handshake. If iframe onload fires, we don't do anything because we are waiting for handshake.
} else {
iframe.onload = () => {
clearTimeout(timeoutId);
setState('success');
};
}
And the overall timeout will fire if:
- For handshake widgets: if the handshake doesn't come in time.
- For non-handshake: if the iframe doesn't load in time.
This seems better.
// So we adjust the code accordingly.
Revised plan:
code
- We have a timeout for the overall process (default 5s).
- If the widget supports handshake, we wait for the handshake message. The iframe onload doesn't trigger success.
- If the widget does not support handshake, we wait for iframe onload and then trigger success.
But note: what if the widget supports handshake but the iframe never loads? Then the timeout will fire. That's correct.
What if the widget doesn't support handshake and the iframe loads but the widget inside is broken (so the iframe document is loaded but the widget's JS failed)? We have no way to know, so we assume it's working.
We'll implement accordingly.
Also, we want to sandbox the iframe. We'll set the sandbox attribute to:
code
sandbox="allow-scripts"
This allows scripts to run but prevents the iframe from:
code
- Submitting forms
- Opening popups
- etc.
We might want to allow forms? It depends on the widget. We can make the sandbox attribute configurable.
We'll add a prop sandbox that defaults to "allow-scripts".
Code structure:
We'll use React hooks.
Let's code:
Note: We are using a ref for the container to append the iframe.
We'll also handle the case where the iframe fails to load? The iframe's onerror event? But note: onerror might not fire for network errors in all browsers. We are already using a timeout, so if the iframe doesn't load, the timeout will fire.
Implementation:
We are going to create a component:
code
However, we are conditionally appending the iframe only when we are in the effect. When state becomes 'success' or 'failed', we don't remove the iframe until cleanup? Actually, we remove the iframe on cleanup (unmount) or on timeout (if failed). But on success, we leave the iframe.
Also, note that during loading we show a loading indicator. But what about the iframe? We are appending the iframe immediately. The iframe might take time to load. We are showing a loading indicator until we get success or timeout.
But the iframe is already in the DOM during loading. That's okay.
However, if the widget is large and we show a loading indicator, we might want to hide the iframe until it's ready? But then we would see a flash when it appears.
Alternatively, we can set the iframe to be hidden until success? We can set iframe.style.visibility = 'hidden' and then set to 'visible' on success.
But then if the widget has a background that we don't want to show, we can do that.
We'll do:
code
When we create the iframe, set iframe.style.visibility = 'hidden';
Then on success, set iframe.style.visibility = 'visible';
And on timeout (failed), we remove the iframe.
But then if the widget fails to load, we remove the iframe and show the fallback.
Let's adjust:
code
In the effect:
iframe.style.visibility = 'hidden';
Then on success (handshake or onload for non-handshake) we set iframe.style.visibility = 'visible';
But note: if the widget is non-handshake and we wait for onload, we set visibility to visible on onload.
If the widget is handshake, we set visibility to visible when we get the handshake.
Also, we must set the iframe to be visible only if we are in success? But we are setting state to success and then setting visibility. But what if the iframe is already visible because of a previous load? We are creating a new iframe each time, so it starts hidden.
This should work.
Let's code accordingly.
However, we must be cautious: if the widget takes a long time to load, the iframe will be there but hidden. That's okay.
Also, we might want to set a minimum size for the container so that the layout doesn't shift when the iframe appears? We can set the container to have a fixed size? That's up to the user.
We'll leave the styling to the user.
Now, the fallback UI: we are given a fallback prop. We show it when state is 'failed'.
We also provide a reload function that we can use in the fallback. But note: the fallback is provided by the user, so we need to give them a way to trigger reload.
We can do:
code
We pass a `reload` function as a prop to the fallback? But the fallback is a React node, not a function.
Alternatively, we can design the fallback as a function that receives the reload function.
But the prop is called fallback and it's a React node. We can change it to:
Alternatively, we can always pass the reload function as a prop to the wrapper and let the user use it in their fallback component? But the fallback is just a node.
Another idea: we can provide a onRetry callback that the user can use in their fallback? But then the fallback would have to call that.
We can do:
code
We provide a `reload` function and the user can use it in their fallback by closing over it? But the fallback is defined outside and doesn't have access.
This way, if they passed a function, we call it with reload. If they passed a node, we ignore the reload.
But then in the static fallback, they cannot use the reload button. That's acceptable because they didn't ask for it.
We can also pass the reload function as a prop to the node? We can't because it's a node.
So we stick with the above.
Let's code accordingly.
One more thing: we are removing the iframe on timeout (failed). But what about when we reload? We remove the old iframe and create a new one.
We are doing that in the effect cleanup.
Now, let's put it all together.
We'll also add an error callback for when the widget times out? We already call onError in the timeout.
We might also want to call onError when the iframe fails to load? But we don't have an event for that. We rely on timeout.
So we call onError only on timeout.
Code:
We are going to use React and ReactDOM.
Let's write the component.
Note: We are using a lot of hooks and effects. We must be careful with dependencies.
We'll use useRef for the container and iframe.
We'll also use useCallback for the reload function.
We'll use useEffect for the widget loading.
We'll use useState for the state.
Let's code accordingly.
However, note: the user might change the widgetUrl or other props while the component is mounted. The effect will re-run and we will clean up the old iframe and load the new one.
That's acceptable.
We are done.
Let's write the code.
I'll design a comprehensive resiliency system for third-party widgets with timeouts, sandboxing, and graceful fallbacks. Here's a complete implementation:
This system provides production-ready resiliency while maintaining security and user experience. The modular design allows teams to configure different strategies for different third-party widgets based on their criticality and risk profile.
function ThirdPartyWidget({
widgetUrl,
handshakeMessage = 'widget-ready',
timeout = 5000,
fallback = <div>Widget failed to load. <button onClick={reload}>Retry</button></div>,
onError,
supportsHandshake = true,
sandbox = 'allow-scripts',
...iframeProps // any other props for the iframe (like width, height, etc.)
}) {
const containerRef = useRef(null);
const [state, setState] = useState<'loading' | 'success' | 'failed'>('loading');
const iframeRef = useRef(null);
useEffect(() => {
let isMounted = true;
let timeoutId;
const iframe = document.createElement('iframe');
iframe.sandbox = sandbox;
// Set other iframe props from iframeProps? We can do:
Object.assign(iframe, iframeProps);
// We'll set the src. We might want to add a handshake parameter? Not necessary if we use postMessage handshake.
iframe.src = widgetUrl;
// Event handler for messages
const handleMessage = (event) => {
// We might want to check event.origin? Let's skip for now, but in production we should.
if (event.data === handshakeMessage) {
if (isMounted) {
clearTimeout(timeoutId);
setState('success');
window.removeEventListener('message', handleMessage);
}
}
};
window.addEventListener('message', handleMessage);
// If the widget does not support handshake, we set onload to mark success.
if (!supportsHandshake) {
iframe.onload = () => {
if (isMounted) {
clearTimeout(timeoutId);
setState('success');
}
};
}
// Append the iframe
const container = containerRef.current;
container.appendChild(iframe);
iframeRef.current = iframe;
// Set the overall timeout
timeoutId = setTimeout(() => {
if (isMounted) {
setState('failed');
window.removeEventListener('message', handleMessage);
// Remove the iframe? We can leave it or remove. Let's remove to avoid broken widget.
if (container.contains(iframe)) {
container.removeChild(iframe);
}
if (onError) {
onError(new Error('Widget timeout'));
}
}
}, timeout);
return () => {
isMounted = false;
clearTimeout(timeoutId);
window.removeEventListener('message', handleMessage);
if (iframeRef.current && container.contains(iframeRef.current)) {
container.removeChild(iframeRef.current);
}
};
}, [widgetUrl, handshakeMessage, timeout, supportsHandshake, sandbox, onError]);
const reload = () => {
setState('loading');
// We'll re-run the effect by changing a key? Or we can have a state that forces re-mount?
// Alternatively, we can have a key prop on the component that we change on reload.
// But we don't have a key from outside. We can use a state inside to force re-mount.
// Let's change: we'll use a key that we increment on reload.
// We'll change the component to take a `key` from the parent? Or we manage internally.
// Actually, we can do:
// const [reloadCount, setReloadCount] = useState(0);
// And then in the effect, we depend on reloadCount.
// But then the parent would need to pass a new key to reset? We can do both.
// Alternatively, we can have a function that resets the component by remounting it.
// Since we are already using a ref and effect, we can just reset the state and re-run the effect by changing a dependency.
// We'll add a state for reloadKey and increment it on reload.
// But note: the effect will run again when reloadKey changes.
// So:
// const [reloadKey, setReloadKey] = useState(0);
// useEffect(() => { ... }, [reloadKey, ...otherDeps]);
// const reload = () => setReloadKey(prev => prev + 1);
// However, we are already using state for 'loading', 'success', 'failed'. We can just reset the state and re-run the effect by having a key.
// Let's change the component to:
// function ThirdPartyWidget({ ..., key }) { ... }
// But then the parent controls the key. We can also provide a reload function that increments an internal key.
// We'll do:
const [internalKey, setInternalKey] = useState(0);
// Then use internalKey as a dependency in the effect? But we don't want to break when other props change.
// Alternatively, we can have a prop `reload` that is a function that the parent can call to reload, but we also want the fallback's retry button to work.
// We'll manage an internal reload counter.
// But note: the effect should run on every reload, so we add internalKey as a dependency.
// However, we are already using a lot of dependencies. We can do:
// useEffect(() => {
// ... effect body ...
// }, [widgetUrl, handshakeMessage, timeout, supportsHandshake, sandbox, onError, internalKey]);
// And then in reload, we setInternalKey(prev => prev + 1);
// But note: when internalKey changes, the effect will run again and the old iframe will be removed (because of the cleanup) and a new one created.
// This is acceptable.
// So we'll add:
const [reloadKey, setReloadKey] = useState(0);
// And then in the effect, we add reloadKey as a dependency.
// But wait, we are defining reload inside the component and it uses setReloadKey. Then we add reloadKey to the effect's dependencies, but then the effect would run on every render? Because reloadKey changes when we call reload? That's what we want.
// However, we are also using other state and props. We are using setState which doesn't change, and the props are stable if the parent doesn't change them.
// But note: the reload function is recreated on every render. We can use useCallback for reload.
// Let's do:
const reload = useCallback(() => {
setReloadKey(prev => prev + 1);
}, []);
// Then we add reloadKey to the effect dependencies.
// But then when reloadKey changes, the effect runs and we create a new iframe.
// This is good.
// However, we are already using state for the widget state (loading, success, failed). We want to reset that too.
// We can reset the state in the effect when it runs? Actually, the effect runs on every reloadKey change, and we set the state to 'loading' at the beginning of the effect? We don't set it to loading in the effect, we set it when we start? We set state to 'loading' when the component mounts? But when we reload, we want to set it to loading again.
// We can setState('loading') at the beginning of the effect.
// So:
useEffect(() => {
setState('loading');
... rest ...
}, [reloadKey, ...]);
// Then when reloadKey changes, the effect runs, sets state to loading, and then starts loading the widget.
// This is acceptable.
// But note: the effect runs on every reloadKey change, and also on every change of the other dependencies. We want to reload when the widgetUrl changes? That's already in the dependencies.
// So we are covered.
}
return (
<div ref={containerRef} style={{ position: 'relative' }}>
{state === 'loading' && <div>Loading...</div>}
{state === 'failed' && fallback}
{/* We don't render anything for success because the iframe is already appended to the container. */}
</div>
);
}