Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Using HTTP in Dart Components

Warning

Compiling Dart to non-web WebAssembly targets is experimental. This guide requires Dart 3.14.0 or later and Wasmtime 47.0.0 or later.

1. Create a new Dart project

To begin, we’ll start with a fresh Dart package:

dart create -t cli dart_wasm_service
cd dart_wasm_service

To configure this package for WebAssembly components, add tooling dependencies:

dart pub add wasi wasm_components dev:wasm_tools

2. Writing the HTTP handler

The following code can be inserted into bin/dart_wasm_service.dart:

import 'dart:async';
import 'dart:convert';

import 'package:wasi/http.dart';
import 'package:wasi/http/service.dart';
import 'package:wasm_components/wasm_components.dart';

void main() {
  serviceComponent((imports) => _RequestHandler(imports));
}

final class _RequestHandler(final ServiceImports _imports) implements Handler {
  var _requestId = 0;

  @override
  Future<Result<Owned<TypesResponse>, TypesErrorCode>> handle({
    required Owned<TypesRequest> request,
  }) async {
    final headers = _imports.httpTypes.constructorFields();
    _imports.httpTypes.methodFieldsAppend(
      self: headers.borrow(),
      name: 'content-type',
      value: utf8.encode('text/html; charset=utf-8'),
    );

    final responseText =
        '''
<!doctype html>
<html>
<head>
  <title>dart2wasm http server</title>
</head>
<body>
<h1>This website is running Dart!</h1>

<p>
This is request number ${_requestId++} served by this server.
</p>
</body>
</html>
''';

    final (response, _) = _imports.httpTypes.staticResponseNew(
      headers: headers,
      contents: .some(.value(utf8.encode(responseText))),
      trailers: Future.syncValue(.ok(.none)),
    );

    request.drop();
    return .ok(response);
  }
}

3. Build the component

To build the component, use wasm_tools compile:

dart run wasm_tools compile bin/dart_wasm_service.dart

Tip

Because this program uses the wasi package for bindings to WASI definitions, running dart run wasm_tools witgen is not necessary.

4. Serve the component with wasmtime

To run your HTTP service component:

wasmtime serve bin/dart_wasm_service.wasm -O pooling-max-tables-per-module=4

Then, send a request from another terminal:

$ curl -s localhost:8080 | grep request
This is request number 0 served by this server.

Note

The pooling-max-tables-per-module option is required since wasmtime serve restricts this by default, preventing Dart modules from running. serve is the only wasmtime subcommand with this restriction.