Skip to main content

07 - Flutter Web with WebAssembly: Build, Deploy and Limits

What flutter build web --wasm produces: two bundles, a JavaScript fallback, supported browsers, COOP and COEP headers in nginx, and the limits for SEO.

What do you think about this article?

At a Glance

What flutter build web --wasm produces: two bundles, a JavaScript fallback, supported browsers, COOP and COEP headers in nginx, and the limits for SEO.

What flutter build web --wasm really produces

The command does not produce a WebAssembly-only app: it produces two versions of the same app in the build/web folder, one for each compilation target. The Flutter web release guide calls them "dual-target": main.dart.wasm with its main.dart.mjs module for browsers that can run Wasm, and main.dart.js (compiled with dart2js) for all the others. At startup the flutter_bootstrap.js script checks that the browser has the required features and chooses by itself. All the rules in this article follow from that: you must serve both versions, you must know which one is running, and the speed gain is not guaranteed to all your visitors.

A second point needs clearing up right away because many articles confuse it. CanvasKit and Skwasm are not alternatives to Wasm: they are Flutter Web's two renderers, that is, the way the interface is drawn (the web support page describes them as the two engines that use WebGL and WebGPU). The --wasm flag changes the compiler of the Dart code, not the choice of renderer, and multi-threaded rendering requires precise HTTP headers. How this relates to the earlier chapters of the series: if you want to understand what the rendering engine does, start from performance and jank.

A statement of method before going on. Dart 3.12.2 and Flutter 3.44.2 are the versions installed on this machine; the official documentation, accessed 2026-11-12, describes Flutter 3.50. I did not run flutter build web on a Flutter project, so everything about the bundle structure comes from the official guides cited; instead I compiled and ran a minimal program in three ways with the Dart tools, and that is what the first listing shows.

How to tell whether your app is running in Wasm

Since the browser can fall back to JavaScript without telling anyone, you need a check inside the program. The Flutter documentation points to two: the compile-time constant bool.fromEnvironment('dart.tool.dart2wasm'), which the Wasm compiler sets to true, and the comparison identical(double.nan, double.nan), which depends on how numbers are represented. I compiled the same file with dart compile wasm and with dart compile js, and also ran it on the VM, to see what the two checks say.

One program, three ways to run it
const isRunningWithWasm = bool.fromEnvironment('dart.tool.dart2wasm');

void main() {
  final byNumbers = identical(double.nan, double.nan);
  print('dart2wasm compile flag: $isRunningWithWasm');
  print('identical(nan, nan): $byNumbers');
}

// Output:
// dart run probe.dart                     -> false / true
// node run_wasm.mjs (dart compile wasm)   -> true / true
// node probe.js     (dart compile js)     -> false / false
// (the two columns are: dart2wasm flag / identical(nan, nan))

The constant is the reliable check: it is true only in the Wasm run. The identical(nan, nan) comparison instead tells JavaScript (where it is false) from anything with native numbers, and so in a browser it does not separate Wasm from anything else; that is why the guide presents it as an alternative. The run_wasm.mjs file below is the minimal loader I used with Node 24 to run the compiled module: it imports the generated .mjs file, compiles the bytes of the .wasm, instantiates the module and calls invokeMain.

Loader to run the Wasm module with Node
import { readFile } from 'node:fs/promises';
const runtime = await import('./probe.mjs');
const bytes = await readFile('./probe.wasm');
const compiled = await runtime.compile(bytes);
const instance = await compiled.instantiate({});
await instance.invokeMain();

In the real app you do not need a loader, because flutter_bootstrap.js does it; here it serves to show that the outcome depends on the compiler and not on your code. The file sizes of the minimal program are another reproducible measurement: they say nothing about the weight of a real app, but they show that Wasm produces two files (the module and its JavaScript loader) and not one.

The commands and the bytes produced (minimal program)
dart compile wasm probe.dart -o probe.wasm   # produces probe.wasm and probe.mjs
dart compile js probe.dart -o probe.js
ls -l probe.wasm probe.mjs probe.js | awk '{print $5, $9}'

// Output:
// 12219 probe.js
// 10899 probe.mjs
// 8927 probe.wasm

Which browsers run it

Compatibility changes with every Flutter version, so the table is the one from the Wasm support guide accessed 2026-11-12, referring to Flutter 3.50. To run Wasm the browser must support WasmGC, "JS String Builtins" and phase 4 exception handling; flutter_bootstrap.js checks these features and the wasmAllowList parameter before choosing the bundle.

EngineMinimum version for WasmBehaviour with --wasm
Chromium (Chrome, Edge, Opera, Brave)137 (desktop and Android)Wasm by default
WebKit (Safari, and all iOS browsers)Safari 26.2 (macOS and iOS)falls back to dart2js with CanvasKit, until you set wasmAllowList: { webkit: true }
Gecko (Firefox)147falls back to dart2js with CanvasKit, until you set wasmAllowList: { gecko: true }

The practical reading is that today Wasm is the default path only on recent Chromium browsers, while Safari and Firefox use it only if you enable it and the version allows it. Anyone opening the site with an older browser receives the JavaScript bundle and the app works all the same: that is why you must never remove main.dart.js from the server.

The headers that enable multiple threads

Multi-threaded rendering uses SharedArrayBuffer, which browsers grant only to "cross-origin isolated" documents, to limit side-channel attacks. According to MDN, a document is isolated if the response contains Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy with the value require-corp or credentialless. Flutter says it plainly: a Wasm app does not run multi-threaded if the server does not send those headers. It is not an error: the app starts all the same, just with less parallelism. How much slower it is depends on your app; the guide gives no percentage and I do not write one.

Before touching nginx it helps to have a way to check what a server really answers. The program below applies MDN's rule to the headers of a response, and to show that the check tells the two cases apart it opens two small local servers, one configured correctly and one that forgets COEP; point it at your own address by replacing the test-servers part with an HttpClient aimed at your site.

Checking the isolation headers
import 'dart:io';

/// Says whether an HTTP response makes the document "cross-origin isolated".
/// Rule (MDN, Window.crossOriginIsolated): COOP == same-origin and
/// COEP in {require-corp, credentialless}.
String verdict(HttpHeaders h) {
  final coop = h.value('cross-origin-opener-policy');
  final coep = h.value('cross-origin-embedder-policy');
  final ok = coop == 'same-origin' &&
      (coep == 'require-corp' || coep == 'credentialless');
  return 'COOP=${coop ?? '(missing)'}, COEP=${coep ?? '(missing)'} '
      '-> ${ok ? 'isolated: SharedArrayBuffer available' : 'NOT isolated: a single thread'}';
}

Future<void> main() async {
  // Two in-process fake servers: one configured correctly, one forgetting COEP.
  final good = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  final broken = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  good.listen((r) {
    r.response.headers
      ..set('Cross-Origin-Opener-Policy', 'same-origin')
      ..set('Cross-Origin-Embedder-Policy', 'require-corp');
    r.response.close();
  });
  broken.listen((r) {
    r.response.headers.set('Cross-Origin-Opener-Policy', 'same-origin');
    r.response.close();
  });

  final client = HttpClient();
  for (final (name, server) in [('good', good), ('broken', broken)]) {
    final req = await client.headUrl(Uri.parse('http://127.0.0.1:${server.port}/'));
    final res = await req.close();
    print('$name: ${verdict(res.headers)}');
  }
  client.close();
  await good.close();
  await broken.close();
}

// Output:
// good: COOP=same-origin, COEP=require-corp -> isolated: SharedArrayBuffer available
// broken: COOP=same-origin, COEP=(missing) -> NOT isolated: a single thread

The second server shows the most common failure: COOP present and COEP forgotten are enough to fall back to a single thread, and nothing in the browser flags it as an error. In the console you can check the same fact with window.crossOriginIsolated, the property MDN documents as the final result of these two headers.

The nginx configuration, with the inheritance trap

In nginx the add_header directive has a rule that surprises: the documentation of ngx_http_headers_module states that headers are inherited from the higher level "if and only if" there is no add_header at the current level. In other words: if you put COOP and COEP in the server block and then add an add_header Cache-Control inside a location, that location no longer sends the two isolation headers. It is a defect that is easy to introduce without noticing. The simplest fix is to put the headers in a file to include in every location that needs them.

The shared snippet
# /etc/nginx/snippets/flutter-isolation.conf
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
The server block (pattern to adapt, nginx not installed here)
server {
    listen 443 ssl;
    server_name app.example.com;
    root /var/www/flutter-web/build/web;

    # index.html: never in long cache, and with the isolation headers
    location = /index.html {
        include snippets/flutter-isolation.conf;
        add_header Cache-Control "no-cache" always;
    }

    # .wasm and .mjs: explicit MIME type, hashed names, long cache
    location ~* \.wasm$ {
        types { }
        default_type application/wasm;
        include snippets/flutter-isolation.conf;
        add_header Cache-Control "public, max-age=31536000, immutable" always;
    }

    location / {
        include snippets/flutter-isolation.conf;
        try_files $uri $uri/ /index.html;
    }
}

This block is a pattern to adapt: nginx is not installed on this machine, so I could not run nginx -t, and the first thing to do on your server is exactly that command. Three lines deserve attention. types { } empties the MIME type table for the location, and default_type application/wasm assigns the right type: the Dart deployment guide explains that without Content-Type: application/wasm streaming compilation fails or waits for the full download. immutable with a one-year cache is legitimate only if the file names contain a hash of the content, while index.html must have no-cache, otherwise visitors stay stuck on an old version. Finally always makes the headers be sent on error responses too.

Compression, cache and atomic release

The Dart deployment guide recommends pre-compressing the .wasm and .mjs files with Brotli (brotli -q 11) and Gzip (gzip -9) already at release time, and writes that WasmGC binaries compress by 35-50% with Brotli. It is a figure from the documentation and not my measurement: it depends on the app. Serving the already compressed files requires the server to know how to do it: in nginx pre-compressed Gzip is enabled with gzip_static (a module to include in the build), while Brotli needs a third-party module installed separately.

  • One release at a time: main.mjs, main.wasm and any deferred modules must be published from the same build, because the .mjs file contains indexes tied to that exact .wasm.
  • Hashed names and long cache: with the content in the file name you can use max-age=31536000, immutable; index.html with no-cache.
  • Deferred modules: in Flutter 3.50 they are enabled with --enable-wasm-deferred-loading, and are not compatible with --web-content-hash.
  • Inline bootstrap: embedding flutter_bootstrap.js in index.html avoids one network request before main.dart.wasm is downloaded.

The point that causes the most incidents is the first: an old .mjs file cached by the browser, paired with a new .wasm, produces an instantiation error. That is why it pays to use a release that changes all the names together and does not overwrite files partially. Deferred loading reduces the initial weight but must be measured on your app: I have no figure to offer that holds for everyone.

SEO: when Flutter Web is not the right tool

The Flutter web FAQ states that Flutter's web output favours performance, fidelity and consistency, and that for this reason the output does not match what search engines expect for indexing. The web support page adds that text-rich content, such as the articles of a blog, suits the web's document model better, and points to Jaspr (Dart, but not Flutter) for traditional sites. If you need SEO, the FAQ's advice is to separate the Flutter application from the landing page and the help pages, written in optimised HTML. So there is no magic configuration that makes a Flutter app indexable: it is a project decision to make at the start.

Frequently asked questions

Do I have to choose between Skwasm and CanvasKit?

With --wasm the bundle includes both paths: in the JavaScript fallback CanvasKit is used, and in the Wasm path Flutter's Wasm rendering engine. The choice is made by flutter_bootstrap.js based on the browser; you intervene only with wasmAllowList.

Are the COOP and COEP headers mandatory?

To start the app, no; to use multiple threads, yes. Watch the side effects: with require-corp every cross-origin resource (images, fonts, scripts) must declare permission with CORS or CORP. If you load resources from other domains, consider credentialless, which the Flutter guide accepts as an alternative.

Can I use dart:html in the app?

No: the documentation declares dart:html, dart:js and package:js not supported with Wasm and slated for removal. You migrate to package:web and to dart:js_interop. Even without --wasm, flutter build web runs a dry run and prints a "Wasm dry run failed" warning if it finds incompatibilities.

What you can do now

You know what the bundle produced by --wasm contains and why the JavaScript fallback must not be removed, you can verify from inside the app which of the two is running, you know which browsers really run Wasm according to the documentation, and you can configure the headers avoiding the add_header trap. What is left is to measure performance on your app with the tools described in the article on performance; for the details of what happens in the framework before drawing, see the Flutter internals.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects