pub struct Handler { /* private fields */ }Expand description
Configurable request handler with before/after middleware hooks.
§Example
use dioxus_cloudflare::Handler;
use worker::*;
#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
unsafe { __wasm_call_ctors(); }
Handler::new()
.before(|req| {
// Short-circuit OPTIONS requests for CORS preflight
if req.method() == worker::Method::Options {
let mut resp = Response::empty()?;
resp.headers_mut().set("Access-Control-Allow-Origin", "*")?;
resp.headers_mut().set("Access-Control-Allow-Methods", "GET,POST,OPTIONS")?;
return Ok(Some(resp));
}
Ok(None) // continue to Axum dispatch
})
.after(|resp| {
resp.headers_mut().set("Access-Control-Allow-Origin", "*")?;
Ok(())
})
.handle(req, env)
.await
}Implementations§
Source§impl Handler
impl Handler
Sourcepub fn before(
self,
hook: impl Fn(&Request) -> Result<Option<Response>> + 'static,
) -> Self
pub fn before( self, hook: impl Fn(&Request) -> Result<Option<Response>> + 'static, ) -> Self
Add a before-dispatch hook.
Runs after context is set (so cf::env(), cf::d1(), etc. work),
before Axum dispatch. Return Ok(None) to continue,
Ok(Some(resp)) to short-circuit with a custom response.
Hooks run in the order they were added.
Sourcepub fn after(self, hook: impl Fn(&mut Response) -> Result<()> + 'static) -> Self
pub fn after(self, hook: impl Fn(&mut Response) -> Result<()> + 'static) -> Self
Add an after-dispatch hook.
Runs after cookies are applied, before returning the response. Use this to add headers, log, or modify the final response.
After hooks also run on short-circuited responses from before hooks. Hooks run in the order they were added.
Sourcepub fn session(self, config: SessionConfig) -> Self
pub fn session(self, config: SessionConfig) -> Self
Configure session middleware.
When enabled, cf::session() becomes available in server functions.
Session data is persisted to the configured backend (KV or D1) and
a session cookie is managed automatically.
§Example
use dioxus_cloudflare::prelude::*;
Handler::new()
.session(SessionConfig::kv("SESSIONS"))
.handle(req, env)
.awaitSourcepub fn websocket<F, Fut>(self, path: &str, handler: F) -> Self
pub fn websocket<F, Fut>(self, path: &str, handler: F) -> Self
Add a WebSocket upgrade route.
When a request has the Upgrade: websocket header and its path starts
with path, the handler is called instead of dispatching through Axum.
The handler receives the owned worker::Request (to forward to a
Durable Object stub, for example).
WebSocket routes are checked after context is set and before hooks run, but before Axum dispatch.
§Example
Handler::new()
.websocket("/ws", |req| async move {
let ns = cf::durable_object("WS_DO")?;
let id = ns.id_from_name("default").cf()?;
let stub = id.get_stub().cf()?;
Ok(stub.fetch_with_request(req).await.cf()?)
})
.handle(req, env)
.await