
Research
Security News
The Growing Risk of Malicious Browser Extensions
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
@rsbuild/plugin-assets-retry
Advanced tools
An Rsbuild plugin to automatically resend requests when static assets fail to load.
English | 简体中文
You can install the plugin using the following command:
# npm
npm add @rsbuild/plugin-assets-retry -D
# yarn
yarn add @rsbuild/plugin-assets-retry -D
# pnpm
pnpm add @rsbuild/plugin-assets-retry -D
# bun
bun add @rsbuild/plugin-assets-retry -D
You can register the plugin in the rsbuild.config.ts
file:
import { pluginAssetsRetry } from "@rsbuild/plugin-assets-retry";
export default {
plugins: [pluginAssetsRetry()],
};
You can configure the retry behavior for assets retry through the options.
type AssetsRetryHookContext = {
times: number;
domain: string;
url: string;
tagName: string;
isAsyncChunk: boolean;
};
type AssetsRetryOptions = {
type?: string[];
domain?: string[];
max?: number;
test?: string | ((url: string) => boolean);
crossOrigin?: boolean | "anonymous" | "use-credentials";
inlineScript?: boolean;
delay?: number | ((context: AssetsRetryHookContext) => number);
onRetry?: (context: AssetsRetryHookContext) => void;
onSuccess?: (context: AssetsRetryHookContext) => void;
onFail?: (context: AssetsRetryHookContext) => void;
};
const defaultAssetsRetryOptions = {
type: ["script", "link", "img"],
domain: [],
max: 3,
test: "",
crossOrigin: false,
delay: 0,
onRetry: () => {},
onSuccess: () => {},
onFail: () => {},
};
string[]
[]
Specifies the retry domain when assets fail to load. In the domain
array, the first item is the default domain of static assets, and the following items are backup domains. When a asset request for a domain fails, Rsbuild will find that domain in the array and replace it with the next domain in the array.
For example:
// rsbuild.config.ts
defineConfig({
plugins: [
pluginAssetsRetry({
domain: ["cdn1.com", "cdn2.com", "cdn3.com"],
})
],
output: {
assetPrefix: "https://cdn1.com", // or "//cdn1.com"
},
});
After adding the above configuration, when assets fail to load from the cdn1.com
domain, the request domain will automatically fallback to cdn2.com
.
If the assets request for cdn2.com
also fails, the request will fallback to cdn3.com
.
string[]
['script', 'link', 'img']
Used to specify the HTML tag types that need to be retried. By default, script tags, link tags, and img tags are processed, corresponding to JS code, CSS code, and images.
For example, only script tags and link tags are processed:
pluginAssetsRetry({
type: ["script", "link"],
});
number
3
The maximum number of retries for a single asset. For example:
pluginAssetsRetry({
max: 5,
});
string | ((url: string) => boolean) | undefined
undefined
The test function of the asset to be retried. For example:
pluginAssetsRetry({
test: /cdn\.example\.com/,
});
undefined | boolean | 'anonymous' | 'use-credentials'
same as html.crossorigin
When initiating a retry for assets, Rsbuild will recreate the <script>
tags. This option allows you to set the crossorigin
attribute for these tags.
By default, the value of crossOrigin
will be consistent with the html.crossorigin
configuration, so no additional configuration is required. If you need to configure the recreated tags separately, you can use this option, for example:
pluginAssetsRetry({
crossOrigin: true,
});
undefined | (context: AssetsRetryHookContext) => void
The callback function when the asset is being retried. For example:
pluginAssetsRetry({
onRetry: ({ times, domain, url, tagName, isAsyncChunk }) => {
console.log(
`Retry ${times} times, domain: ${domain}, url: ${url}, tagName: ${tagName}, isAsyncChunk: ${isAsyncChunk}`
);
},
});
undefined | (context: AssetsRetryHookContext) => void
The callback function when the asset is successfully retried. For example:
pluginAssetsRetry({
onSuccess: ({ times, domain, url, tagName, isAsyncChunk }) => {
console.log(
`Retry ${times} times, domain: ${domain}, url: ${url}, tagName: ${tagName}, isAsyncChunk: ${isAsyncChunk}`
);
},
});
undefined | (context: AssetsRetryHookContext) => void
The callback function when the asset is failed to be retried. For example:
pluginAssetsRetry({
onFail: ({ times, domain, url, tagName, isAsyncChunk }) => {
console.log(
`Retry ${times} times, domain: ${domain}, url: ${url}, tagName: ${tagName}, isAsyncChunk: ${isAsyncChunk}`
);
},
});
type AddQuery =
| boolean
| ((context: { times: number; originalQuery: string }) => string);
false
Whether to add query when retrying resources, so as to avoid being affected by browser and CDN caches on the retry results.
When set to true
, retry=${times}
will be added to the query when requesting, and requests will be made in sequence according to retry=1
, retry=2
, retry=3
etc, for example:
Assume that the requested asset is https://js.cdn.net/foo.js
. If the request fails, it will automatically retry https://js.cdn.net/foo.js?retry=${times}
Assume that the requested asset is https://js.cdn.net/foo.js?version=1
. If the request fails, it will automatically retry https://js.cdn.net/foo.js?version=1&retry=${times}
When you want to customize query, you can pass a function, for example:
pluginAssetsRetry({
addQuery: ({ times }) => {
return times === 3
? `?retryCount=${times}&isLast=1`
: `?retryCount=${times}`;
},
});
originalQuery
:pluginAssetsRetry({
addQuery: ({ times, originalQuery }) => {
const query =
times === 3 ? `retryCount=${times}&isLast=1` : `retryCount=${times}`;
return originalQuery ? `${originalQuery}&${query}` : `?${query}`;
},
});
boolean
true
Whether to inline the runtime JavaScript code of Assets Retry plugin into the HTML file.
If you don't want to insert the code in the HTML file, you can set inlineScript
to false
:
pluginAssetsRetry({
inlineScript: false,
});
After adding the above configuration, the runtime code of Assets Retry plugin will be extracted into a separate assets-retry.[version].js
file and output to the dist directory.
The downside is that assets-retry.[version].js
itself may fail to load. If this happens, the assets retry will not work. Therefore, we prefer to inline the runtime code into the HTML file.
boolean
process.env.NODE_ENV === 'production'
Configure whether to enable code minification for runtime JavaScript code.
By default, it will be affected by the output.minify configuration.
pluginAssetsRetry({
minify: true,
});
number | ((context: AssetsRetryHookContext) => number)
0
The delay time (in milliseconds) before retrying a failed asset.
You can pass a number:
// Delay 1s before retrying
pluginAssetsRetry({
delay: 1000,
});
Or pass a function that receives AssetsRetryHookContext
and returns the delay time:
// Calculate delay based on retry attempts
pluginAssetsRetry({
delay: (ctx) => (ctx.times + 1) * 1000,
});
When you use Assets Retry plugin, the Rsbuild injects some runtime code into the HTML and Rspack Runtime, then serializes the Assets Retry plugin config, inserting it into the runtime code. Therefore, you need to be aware of the following:
onRetry
, onSuccess
, and onFail
.onRetry
, onSuccess
and onFail
as these functions are inlined directly into the HTML.Here's an example of incorrect usage:
import { someMethod } from "utils";
pluginAssetsRetry({
onRetry() {
// Incorrect usage, includes sensitive information
const privateToken = "a-private-token";
// Incorrect usage, uses an external method
someMethod(privateToken);
},
});
Assets Retry plugin may not work in the following scenarios:
For remote modules loaded by Module Federation, you can use the @module-federation/retry-plugin from Module Federation 2.0 to implement static asset retries.
If your project is a micro-frontend application (such as a Garfish sub-application), the assets retry may not work because micro-frontend sub-applications are typically not loaded directly based on the <script>
tag.
If you need to retry assets in micro-frontend scenarios, please contact the developers of the micro-frontend framework to find a solution.
Assets Retry plugin listens to the page error event to know whether the current resource fails to load and needs to be retried. Therefore, if the resource in the custom template is executed earlier than Assets Retry plugin, then Assets Retry plugin cannot listen to the event that the resource fails to load, so it will not be retried.
If you want Assets Retry plugin to work on resources in custom templates, you can refer to Custom Insertion Example to modify html.inject configuration and custom template.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>custom template</title>
+ <%= htmlPlugin.tags.headTags %>
<script src="https://example.com/assets/a.js"></script>
</head>
<body>
<div id="root" />
+ <%= htmlPlugin.tags.bodyTags %>
</body>
</html>
MIT.
FAQs
The npm package @rsbuild/plugin-assets-retry receives a total of 17,216 weekly downloads. As such, @rsbuild/plugin-assets-retry popularity was classified as popular.
We found that @rsbuild/plugin-assets-retry demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
Research
Security News
An in-depth analysis of credential stealers, crypto drainers, cryptojackers, and clipboard hijackers abusing open source package registries to compromise Web3 development environments.
Security News
pnpm 10.12.1 introduces a global virtual store for faster installs and new options for managing dependencies with version catalogs.