Security: Validating Message Origins
You'll learn how to verify message senders to prevent accepting data from malicious or unexpected sources.
Why Origin Validation Matters
When using postMessage to communicate between workers, iframes, or windows, any context that has a reference to your window can send it messages. Without checking who sent the message, you're vulnerable to attacks where malicious code injects harmful data or commands into your application.
Think of it like receiving mail: just because a letter arrives at your door doesn't mean you should trust its contents. You check the return address first.
The Origin Property
Every message event includes an origin property that tells you the URL origin (protocol + host + port) of the sender. You should always validate this before processing the message data.
// In your worker or main thread message handler
self.addEventListener('message', (event) => {
// BAD: Processing without checking
// processData(event.data);
// GOOD: Validate first
if (event.origin !== 'https://trusted-domain.com') {
console.warn('Rejected message from untrusted origin:', event.origin);
return;
}
// Safe to process now
processData(event.data);
});
Best Practices
- Whitelist known origins: Only accept messages from domains you explicitly trust
- Be specific: Use full URLs (
https://example.com) not wildcards - Fail closed: Reject unknown origins by default
- Log suspicious activity: Track rejected messages for security monitoring
Key Takeaway: Always check event.origin in message handlers before processing event.data to prevent accepting messages from untrusted or malicious sources.