Expand description

Axum Browser Adapter

A collection of tools to make integrating Axum with the browser easier

Example

use axum_browser_adapter::{
    wasm_request_to_axum_request,
    axum_response_to_wasm_response,
    wasm_compat,
    WasmRequest,
    WasmResponse
};
use axum::Router;
use axum::routing::get;
use wasm_bindgen::prelude::wasm_bindgen;
use tower_service::Service;

#[wasm_compat]
pub async fn index() -> &'static str {
    "Hello World"
}

#[wasm_bindgen]
pub async fn wasm_app(wasm_request: WasmRequest) -> WasmResponse {
   let mut router: Router = Router::new().route("/", get(index));

   let request = wasm_request_to_axum_request(&wasm_request).unwrap();

   let axum_response = router.call(request).await.unwrap();

   let response = axum_response_to_wasm_response(axum_response).await.unwrap();

   response
}

Integrating w/ the browser

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="module">
    import init, {wasm_app, WasmRequest} from './dist/example.js';

    (async function () {
        await init();

        const wasmRequest = new WasmRequest("GET", "/", {}, undefined);
        let response = await wasm_app(wasmRequest);

        document.write(response.body)
    }())
</script>
</body>
</html>

Recipes

You might want to override fetch or use a service worker to intercept HTTP calls in order to the call the Axum WASM app instead of the a HTTP server.

Converting a JavaScript Request to a WasmRequest

 async function requestToWasmRequest(request) {
    const method = request.method;
    const url = request.url;
    const headers = Object.fromEntries(request.headers.entries());

    let body = null;
    if (request.body !== null) {
        body = await request.text();
    }
    return new WasmRequest(method, url, headers, body);
}

Converting a WasmResponse to a JavaScript Response

function wasmResponseToJsResponse(wasmResponse) {
   const body = wasmResponse.body;
   const status = parseInt(wasmResponse.status_code);
   const jsHeaders = new Headers();
   const headers = wasmResponse.headers;
   for (let [key, value] of headers) {
       jsHeaders.append(key, value);
   }
   return new Response(body, {status: status, headers: jsHeaders});
}

Structs

Functions

Attribute Macros