# @module-federation/retry-plugin > A robust retry plugin for Module Federation that provides automatic retry mechanisms for failed module requests with domain rotation, cache-busting, and comprehensive error handling. ## Features - 🔄 **Automatic Retry**: Automatically retries failed fetch and script requests - 🌐 **Domain Rotation**: Rotate through multiple domains for better reliability - ⚡ **Cache Busting**: Add query parameters to bypass cache issues - 📊 **Lifecycle Callbacks**: Comprehensive callbacks for retry events - 🎯 **Flexible Configuration**: Highly configurable retry strategies - 🔧 **TypeScript Support**: Full TypeScript support with type definitions ## Installation ```bash npm install @module-federation/retry-plugin # or yarn add @module-federation/retry-plugin # or pnpm add @module-federation/retry-plugin ``` ## Basic Usage ### Runtime Plugin Registration ```ts import { createInstance } from '@module-federation/enhanced/runtime'; import { RetryPlugin } from '@module-federation/retry-plugin'; const mf = createInstance({ name: 'host', remotes: [ { name: 'remote1', entry: 'http://localhost:2001/mf-manifest.json', }, ], plugins: [ RetryPlugin({ retryTimes: 3, retryDelay: 1000, domains: ['https://cdn1.example.com', 'https://cdn2.example.com'], manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'], addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`, onRetry: ({ times, url }) => console.log('Retrying...', times, url), onSuccess: ({ url }) => console.log('Success!', url), onError: ({ url }) => console.log('Failed!', url), }), ], }); ``` ### Build Plugin Registration ```ts // webpack.config.js import { ModuleFederationPlugin } from '@module-federation/webpack'; import { RetryPlugin } from '@module-federation/retry-plugin'; export default { plugins: [ new ModuleFederationPlugin({ name: 'host', remotes: { remote1: 'remote1@http://localhost:2001/mf-manifest.json', }, runtimePlugins: [path.join(__dirname, './src/runtime-plugin/retry.ts')], }), ], }; ``` ```ts // src/runtime-plugin/retry.ts import { RetryPlugin } from '@module-federation/retry-plugin'; export default () => RetryPlugin({ retryTimes: 3, retryDelay: 1000, domains: ['https://cdn1.example.com', 'https://cdn2.example.com'], manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'], addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`, onRetry: ({ times, url }) => console.log('Retrying...', times, url), onSuccess: ({ url }) => console.log('Success!', url), onError: ({ url }) => console.log('Failed!', url), }); ``` ## Configuration Options ### CommonRetryOptions | Option | Type | Default | Description | | ----------------- | --------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------ | | `retryTimes` | `number` | `3` | Number of retry attempts | | `retryDelay` | `number \| (attempt: number) => number` | `1000` | Delay between retries in milliseconds, or a function returning delay per 1-indexed retry attempt | | `successTimes` | `number` | `0` | Number of successful requests required | | `domains` | `string[]` | `[]` | Alternative domains for script resources | | `manifestDomains` | `string[]` | `[]` | Alternative domains for manifest files | | `addQuery` | `boolean \| function` | See below | Add query parameters for cache busting | | `fetchOptions` | `RequestInit` | `{}` | Additional fetch options | | `onRetry` | `function` | `undefined` | Callback when retry occurs | | `onSuccess` | `function` | `undefined` | Callback when request succeeds | | `onError` | `function` | `undefined` | Callback when all retries fail | ### addQuery Function When omitted, `addQuery` defaults to `true` only for `esm` and `module` remote entry retries. This gives failed dynamic imports a new URL because browsers cache their failures by URL. Manifest, fetch, and classic script retries still default to no query parameter. Set `addQuery: false` to disable the ESM/module default. ```ts addQuery: ({ times, originalQuery }) => { // Add retry count and timestamp for cache busting const separator = originalQuery ? '&' : '?'; return `${originalQuery}${separator}retry=${times}&t=${Date.now()}`; }; ``` ### Callback Functions ```ts onRetry: ({ times, domains, url, tagName }) => { console.log(`Retry attempt ${times} for ${url}`); console.log(`Available domains: ${domains?.join(', ')}`); }, onSuccess: ({ domains, url, tagName }) => { console.log(`Successfully loaded ${url}`); console.log(`Used domain: ${domains?.[0]}`); }, onError: ({ domains, url, tagName }) => { console.error(`Failed to load ${url} after all retries`); console.error(`Tried domains: ${domains?.join(', ')}`); } ``` ## Advanced Examples ### Custom Retry Strategy ```ts RetryPlugin({ retryTimes: 5, retryDelay: (attempt) => 1000 * 2 ** (attempt - 1), // Exponential backoff: 1s, 2s, 4s, ... domains: ['https://cdn1.example.com', 'https://cdn2.example.com', 'https://cdn3.example.com'], manifestDomains: ['https://api1.example.com', 'https://api2.example.com'], addQuery: ({ times, originalQuery }) => { const params = new URLSearchParams(originalQuery); params.set('retry', times.toString()); params.set('cache_bust', Date.now().toString()); return params.toString(); }, onRetry: ({ times, url, domains }) => { console.log(`Retry ${times}/5 for ${url}`); console.log(`Trying domain: ${domains?.[times % domains.length]}`); }, onSuccess: ({ url, domains }) => { console.log(`✅ Successfully loaded ${url}`); console.log(`✅ Used domain: ${domains?.[0]}`); }, onError: ({ url, domains }) => { console.error(`❌ Failed to load ${url} after all retries`); console.error(`❌ Tried all domains: ${domains?.join(', ')}`); }, }); ``` ### Error Handling with Fallback ```ts RetryPlugin({ retryTimes: 3, retryDelay: 1000, domains: ['https://cdn1.example.com', 'https://cdn2.example.com'], onError: ({ url, domains }) => { // Log error for monitoring console.error('Module loading failed:', { url, domains }); // Send error to monitoring service if (window.gtag) { window.gtag('event', 'module_load_error', { event_category: 'module_federation', event_label: url, value: domains?.length || 0, }); } // Show user-friendly error message const errorElement = document.createElement('div'); errorElement.className = 'module-load-error'; errorElement.innerHTML = `
Unable to load module: ${url}
Please refresh the page to try again.