Control data delivery in Browser SDK 2

このページはまだあなたの言語に翻訳されていません。 現在取り組んでいますので、後でもう一度確認してください。

Browser SDK 2 doesn't send each event as it's tracked. It saves events to a queue in localStorage, uploads them in batches, and retries failed uploads. This page covers each setting that changes that behavior. The defaults suit most sites. Change them when events go missing on navigation, when a network blocks Amplitude's domain, or when you need a specific data region.

How the SDK uploads events

  1. track() adds the event to an in-memory queue and writes the queue to localStorage under AMP_unsent_ plus the first 10 characters of your API key.
  2. flushIntervalMillis (default 1000) after the first event enters the queue, the SDK sends the whole queue, split into requests of up to flushQueueSize (default 30) events. Requests go out one at a time to keep events in order. A full queue doesn't trigger an early upload.
  3. On a 200 response, the SDK removes the events from the queue and storage.
  4. On a failure, the SDK retries. After network errors and 5xx responses, the wait grows by 1 second with each attempt. Throttled events (429) wait 30 seconds. A 413 halves flushQueueSize. After flushMaxRetries (default 5) attempts, the SDK drops the event.
  5. On the next page load, the SDK sends any events still in localStorage.

localStorage holds at most 1,000 unsent events. If the queue grows past that, for example during a long offline period, the SDK logs Failed to save N events because the queue length exceeded 1000 and doesn't persist the extra events. If localStorage isn't available, the SDK keeps the queue in memory only and logs a warning.

ts
amplitude.init("AMPLITUDE_API_KEY", {
  flushIntervalMillis: 5000,
  flushQueueSize: 50,
  flushMaxRetries: 3,
});

To send the queue now, call flush(). It sends every queued event once, without retries.

ts
await amplitude.flush().promise;

Tune upload performance

track() doesn't wait for the network. The SDK queues the event and uploads in the background, so most tuning is a tradeoff between request count and delay:

  • Fewer requests: raise flushIntervalMillis. Events wait longer before they upload. If the page closes first, they stay in localStorage until the user's next visit.
  • Faster delivery: lower flushIntervalMillis. The SDK sends more, smaller requests.
  • Larger requests: raise flushQueueSize when a single flush often holds more than 30 events. Each request carries more events, so a busy queue needs fewer requests. If a request is too large, Amplitude returns 413 and the SDK halves flushQueueSize.
  • High-volume sources: set useBatch: true to send to the Batch Event Upload API, which has higher rate limits. It doesn't reduce the number of requests.

For current bundle size, check the npm package page or BundlePhobia.

Choose a data region

Set serverZone to the data center of your Amplitude organization. The default is US.

ts
amplitude.init("AMPLITUDE_API_KEY", {
  serverZone: "EU",
});

useBatch: true switches to the Batch Event Upload API (/batch), which has higher rate limits for high-volume sources. It doesn't change how the SDK batches events in the browser.

Allow Amplitude in a Content Security Policy

If your site sends a Content-Security-Policy header, allow Amplitude's domains:

text
script-src  https://*.amplitude.com;
connect-src https://*.amplitude.com;

You need script-src only when you load the SDK from Amplitude's CDN with the script loader. connect-src covers event uploads, remote configuration, and SDK diagnostics. If you proxy all traffic through your own domain, allow that domain instead.

Send events when the page unloads

Browsers cancel in-flight requests when a page unloads, so you can lose events tracked right before a navigation, such as a login that redirects.

The default fetch transport sets keepalive on requests with bodies of 16 KB or less, so the browser finishes them after the page unloads. Keepalive keeps compression, custom headers, responses, and retries. Browsers share a 64 KB keepalive budget across all in-flight requests on a page, which is why the SDK sends larger bodies without it. The SDK measures the body after compression. If the browser rejects a keepalive request because the budget is full, the SDK retries on the next flush. Browsers that don't support keepalive ignore the flag and send a normal request.

For bodies larger than 16 KB, switch to the beacon transport when the page hides:

ts
window.addEventListener("pagehide", () => {
  amplitude.setTransport("beacon");
  amplitude.flush();
});

sendBeacon hands the request to the browser and returns immediately. It has these limits:

  • No response, so the SDK can't retry failures. It treats a request the browser accepts as successful.
  • No custom headers, so no compression.
  • No ordering guarantee between requests.

To turn off keepalive, for example to debug a keepalive-specific failure, set enableKeepalive: false:

ts
amplitude.init("AMPLITUDE_API_KEY", {
  transport: { type: "fetch", enableKeepalive: false },
});

Choose a transport

Pass a string, or an object to set options:

ts
amplitude.init("AMPLITUDE_API_KEY", {
  transport: {
    type: "fetch",
    headers: { "X-Request-Source": "web" },
    referrerPolicy: "strict-origin-when-cross-origin",
  },
});
  • headers adds HTTP headers to each upload (fetch and xhr). The SDK always sets Content-Type and Accept, and your headers can't replace them. Custom headers make the request non-simple, so the server must answer a CORS preflight. Amplitude's endpoints do. Check your proxy. Requires Browser SDK 2.33.0 or later.
  • referrerPolicy sets the fetch referrer policy for uploads. Requires Browser SDK 2.44.0 or later.
  • enableKeepalive turns fetch keepalive on or off. It's on by default, a default that changed in 2.43.0.

To change the transport after init(), call setTransport().

Compress request bodies

When the browser supports CompressionStream, the SDK gzip-compresses request bodies of 2 KB or more and sets Content-Encoding: gzip. This is always on for Amplitude's endpoints. For a custom serverUrl, it's off unless you set enableRequestBodyCompression: true, because your server must accept gzip bodies. Compression requires Browser SDK 2.36.0 or later, and the default changed to on for Amplitude's endpoints in 2.42.0.

ts
amplitude.init("AMPLITUDE_API_KEY", {
  serverUrl: "https://collect.example.com/amplitude",
  enableRequestBodyCompression: true,
});

Chrome and Edge 80, Firefox 113, Safari 16.4, and later versions support CompressionStream. Older browsers send uncompressed bodies. The beacon transport never compresses.

Send events through a proxy

Ad blockers and some corporate networks block *.amplitude.com. A proxy on your own domain avoids that. Point serverUrl at the proxy, and forward each request body unchanged to the Amplitude endpoint for your region.

ts
amplitude.init("AMPLITUDE_API_KEY", {
  serverUrl: "https://collect.example.com/amplitude",
  remoteConfig: {
    serverUrl: "https://collect.example.com/amplitude-config",
  },
});

serverUrl overrides serverZone and useBatch for event uploads. remoteConfig.serverUrl routes the remote configuration fetch separately.

Your proxy must:

  • Answer OPTIONS preflight requests and return Access-Control-Allow-Origin for your site. Without it, the browser blocks the request and the console shows has been blocked by CORS policy.
  • Forward the request body and Content-Encoding header unchanged, or decompress before forwarding.
  • Forward the client's IP address, for example in X-Forwarded-For, if you want Amplitude to derive location from it. Otherwise Amplitude records the proxy's IP.
  • Return Amplitude's status code and JSON body unchanged. The SDK reads them to decide whether to retry.

For setup examples, go to Proxy requests.

Work offline

The SDK listens for the browser's online and offline events. While navigator.onLine is false, it keeps events in the queue and doesn't attempt uploads. When the browser comes back online, it uploads the queue after flushIntervalMillis. Requires Browser SDK 2.4.0 or later.

Keep flushIntervalMillis well above a few milliseconds. With a value such as 1, the upload starts almost the moment the online event fires, often before the connection settles, and Chrome can fail it with ERR_NETWORK_CHANGED. The SDK retries the failed upload.

To control connectivity yourself, for example in a webview that reports onLine incorrectly, turn off the built-in check:

ts
amplitude.init("AMPLITUDE_API_KEY", {
  offline: amplitude.Types.OfflineDisabled,
});

With OfflineDisabled, the SDK always attempts uploads and relies on retries.

Store unsent events somewhere else

storageProvider replaces localStorage for the unsent-event queue. Pass any object that implements the Storage interface (isEnabled, get, getRaw, set, remove, reset), or an in-memory store to keep events out of persistent storage:

ts
const memoryQueue = new Map<string, amplitude.Types.Event[]>();

amplitude.init("AMPLITUDE_API_KEY", {
  storageProvider: {
    isEnabled: async () => true,
    get: async (key) => memoryQueue.get(key),
    getRaw: async (key) => JSON.stringify(memoryQueue.get(key)),
    set: async (key, value) => void memoryQueue.set(key, value),
    remove: async (key) => void memoryQueue.delete(key),
    reset: async () => memoryQueue.clear(),
  },
});

With memory-only storage, events still queued when the page unloads are lost. Identity storage is separate. Go to Choose where the SDK stores identity.

これは役に立ちましたか?

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

このページでは