Cloudflare Speedtest

repository·main·Indexed 20 days ago

https://github.com/cloudflare/speedtest

A JavaScript module for measuring client Internet connection quality, including download/upload bandwidth, latency, and packet loss, by leveraging the Cloudflare edge network. It utilizes the PerformanceResourceTiming browser API for precise timing data and supports custom measurement sequences and TURN server integration for packet loss analysis.

Tokens
16.2K
Snippets
45
Records
63
Agent score
72%

What's inside @cloudflare/speedtest

  1. Overview of Cloudflare Speedtest

    main

    The @cloudflare/speedtest module is a JavaScript measurement engine used to evaluate a client's Internet connection quality. It performs test requests against the Cloudflare edge network and utilizes the PerformanceResourceTiming browser API to extract precise timing data.

    Key metrics measured include:

    • Download bandwidth
    • Upload bandwidth
    • Latency
    • Packet loss

    Note: Measurement results are collected by Cloudflare upon completion to help calculate aggregated insights regarding global Internet connection quality.

  2. Monitor SpeedTest state and events

    main

    You can monitor the progress of a speedtest using instance attributes and notification event methods.

    Attributes:

    • isRunning: (boolean) True if the engine is currently running.
    • isFinished: (boolean) True if all measurements are complete and results are final.
    • results: (Results) Getter for the current results object. Note that values may be incomplete while the test is running.

    Events:

    • onRunningChange(running: boolean): Triggered when the engine starts or stops.
    • onResultsChange({ type: string }): Triggered when any item in the results changes (e.g., a measurement completes).
    • onFinish(results: Results): Triggered when the engine finishes all measurements. Returns the final results object.
    • onError(error: string): Triggered when an error occurs during a measurement.
  3. Quickstart with Cloudflare Speedtest

    main

    To perform a basic speed test, import the SpeedTest class, instantiate it, and listen to the onFinish event to retrieve the measurement results. You can use results.getSummary() to get a summarized view of the connection quality.

    import SpeedTest from '@cloudflare/speedtest';
    
    new SpeedTest().onFinish = results => console.log(results.getSummary());
  4. Set up a TURN credentials worker

    main

    The TURN credentials worker provides the measurement engine with necessary TURN server credentials. To set it up, you must first create a Realtime TURN App in the Cloudflare Dashboard to obtain a Turn Token ID and an API Token.

    Local Development Setup

    Edit the .dev.vars file in the root of the worker directory and set the following environment variables:

    • REALTIME_TURN_TOKEN_ID: The Turn Token ID from the dashboard.
    • REALTIME_TURN_TOKEN_SECRET: The API Token from the dashboard.

    Remote Deployment Setup

    Add the secrets to your remote worker using Wrangler:

    npm exec wrangler secret put REALTIME_TURN_TOKEN_ID
    npm exec wrangler secret put REALTIME_TURN_TOKEN_SECRET
  5. Connect the measurement engine to the TURN credentials worker

    main

    When instantiating the measurement engine, you must provide the turnServerCredsApiUrl option to point to your worker's endpoint.

    • Production: Set turnServerCredsApiUrl to https://<your-worker-domain>/turn-credentials.
    • Local Development: Run npm run start and set turnServerCredsApiUrl to http://localhost:8787.
  6. Configure Speedtest options using ConfigOptions

    main

    When initializing or configuring a speedtest, use the ConfigOptions type. This type is a Partial<Config>, meaning you only need to provide the specific configuration properties you wish to override from the defaultConfig.

    Note that the full Config type is intended for internal use and is not part of the public API; consumers should interact with the library using ConfigOptions.

    // Example of how a consumer would use ConfigOptions
    // (Assuming an instantiation method exists that accepts these options)
    const myOptions: ConfigOptions = {
      // provide specific overrides here
    };
  7. Understand the Results class and measurement aggregation

    main

    The Results class aggregates raw measurement data and provides computed metrics such as latency, bandwidth, jitter, packet loss, and AIM experience scores.

    Note for Consumers: Instances of Results are typically created internally by the MeasurementEngine. You should access results through the engine's results property rather than instantiating Results manually.

    Key Concepts

    • Raw Data vs. Computed Metrics: The raw property contains the unprocessed measurement entries. For most use cases (like UI display), you should use the provided getter methods which return typed, computed values.
    • Completion State: The isFinished getter returns true only when all configured measurement types have marked themselves as finished.
    // Accessing results via the engine (conceptual usage)
    const results = engine.results;
    
    if (results.isFinished) {
      const downloadSpeed = results.getDownloadBandwidth();
      const summary = results.getSummary();
    }
  8. Define measurement phases with MeasurementConfig

    main

    The measurements array in your configuration defines an ordered sequence of measurement phases. The engine executes these sequentially.

    • Accumulation: Multiple latency, download, and upload steps accumulate their results.
    • Replacement: Other measurement types, such as packetLoss, replace prior results if multiple steps of the same type are configured.
    • Termination: The engine stops executing further rounds of a bandwidth-type measurement once its bandwidthFinishRequestDuration threshold is reached.
    const measurements: MeasurementConfig[] = [
      { type: 'latency', numPackets: 10 },
      { type: 'download', bytes: 1e6, count: 5 },
      { type: 'packetLoss', numPackets: 100, batchSize: 10, batchWaitTime: 50, responsesWaitTime: 1000 }
    ];
  9. Configure SpeedTest options

    main

    The SpeedTest constructor accepts a configuration object to customize the measurement behavior, API endpoints, and TURN server settings.

    Key configuration options include:

    • autoStart: (boolean) Whether to start measurements immediately. Default: true.
    • downloadApiUrl: (string) URL for download GET requests. Default: https://speed.cloudflare.com/__down.
    • uploadApiUrl: (string) URL for upload POST requests. Default: https://speed.cloudflare.com/__up.
    • turnServerUri: (string) URI of the TURN server for packet loss measurement. Default: turn.cloudflare.com:3478.
    • authorizationToken: (string) An opaque token sent as a jwt query-string parameter to attribute tests to customers. This must be obtained from your own backend.
    • measurements: (array) A custom sequence of measurement objects (see Measurement config).
  10. Configure routes and allowed origins for the TURN worker

    main

    To control where the worker is accessible and which origins are permitted, modify wrangler.jsonc:

    1. Routes: Uncomment the routes section in wrangler.jsonc and replace the example configuration with your specific domain and zone ID. If left unconfigured, the worker will use the default *.workers.dev subdomain.
    2. Allowed Origins: Add the URLs where your worker will be available to the REALTIME_TURN_ORIGINS variable within the vars section of wrangler.jsonc.