Skip to content

[Rust] Don't use the reqwest crate when compiling to wasm #437

@bandogora

Description

@bandogora

Preflight checklist

Ory Network Project

No response

Describe your problem

When compiling for a wasm target the reqwest crate shouldn't be used. We have access to the browser fetch api through the wasm-bindgen and web-sys crates.

Although reqwest does compile for wasm, it's overkill and doesn't yet support the setting the required CSRF cookies or the credentials: include fetch property.

Describe your ideal solution

Use the native browser fetch api through the wasm-bindgen and web-sys crates.

Example:

[dependencies]
gloo-utils = { version = "0.1", features = ["serde"] }
wasm-bindgen = "0.2.100"
wasm-bindgen-futures = "0.4.50"
web-sys = { version = "0.3.77", features = ["Headers", "Request", "RequestInit", "RequestMode", "Response", "Window", "RequestCredentials"] }
use gloo_utils::format::JsValueSerdeExt;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestCredentials, RequestInit, RequestMode, Response};

pub async fn create_browser_registration_flow(
  kratos_browser_url: &str,
) -> Result<ory_kratos_client::models::RegistrationFlow, JsValue> {
  let opts = RequestInit::new();
  opts.set_method("GET");
  opts.set_mode(RequestMode::Cors);
  opts.set_credentials(RequestCredentials::Include);

  let url = format!("{}/self-service/registration/browser", kratos_browser_url);

  let request = Request::new_with_str_and_init(&url, &opts)?;

  request.headers().set("Accept", "application/json")?;

  let window = web_sys::window().unwrap();
  let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;

  // `resp_value` is a `Response` object.
  assert!(resp_value.is_instance_of::<Response>());
  let resp: Response = resp_value.dyn_into().unwrap();

  // Convert this other `Promise` into a rust `Future`.
  let json = JsFuture::from(resp.json()?).await?.into_serde().unwrap();
  Ok(json)
}

Workarounds or alternatives

The only work around I have found when trying to use the Rust SDK on the client side is rewriting the ory_kratos_client::apis::frontend_api functions to use wasm-bindgen.

Version

kratos-client-rust v1.3.8

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    featNew feature or request.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions