Course contentsShow
← Security
Lesson 1067 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Secure postMessage Implementation Patterns

Implementing strict origin validation, data sanitization, and defensive postMessage receiver patterns.

Secure postMessage Implementation Patterns

What you'll learn: How to implement postMessage safely by validating origins, sanitizing data, and building defensive receivers.

The Challenge

After learning that postMessage can be exploited through poor origin validation and data injection, you now need patterns that actually work. Secure postMessage isn't about avoiding the API—it's about using it correctly with multiple layers of defense.

Three Pillars of Secure postMessage

1. Strict Origin Validation

Always validate event.origin against an allowlist of exact origins. Never use substring checks or wildcards:

// Secure receiver
window.addEventListener('message', (event) => {
  const ALLOWED_ORIGINS = ['https://trusted-app.example.com'];
  
  if (!ALLOWED_ORIGINS.includes(event.origin)) {
    console.warn('Rejected message from:', event.origin);
    return; // Stop processing
  }
  
  // Safe to proceed...
});

2. Data Sanitization

Treat event.data as untrusted input. Validate structure and sanitize before use:

// Validate expected format
if (typeof event.data !== 'object' || !event.data.action) {
  return;
}

// Sanitize before DOM insertion
const safeMessage = DOMPurify.sanitize(event.data.text);

3. Defensive Receiver Patterns

Implement an action allowlist instead of executing arbitrary commands:

const ALLOWED_ACTIONS = {
  'update-status': handleStatusUpdate,
  'close-dialog': handleClose
};

if (ALLOWED_ACTIONS[event.data.action]) {
  ALLOWED_ACTIONS[event.data.action](event.data);
}
// Reject anything else by default

Think of it like a secure delivery system: check the sender's ID (origin), inspect the package contents (data validation), and only accept known item types (action allowlist).

Key Takeaway:
Secure postMessage requires strict origin allowlists, comprehensive data validation, and defensive action handling—never trust the sender or the data without verification.