Attribute Macro bindings

Source
#[bindings]
Expand description

Automatically bind bindings in your wrangler.toml into a Rust struct

  • This uses the default (top-level) env by default. You can configure it by passing an env name as argument like #[bindings(dev)]
  • You can the bindings instance by <struct name>::from(&env).

§Example


wrangler.toml

[[kv_namespaces]]
binding = "MY_KV"
id      = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

lib.rs

use worker::*;
use worker_bindings::bindings;
 
#[bindings]
struct Bindings;
 
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
    let b = Bindings::from(&env);
 
    let data = b.MY_KV.get("data").text().await
        .expect("Failed to get data");
 
    //...
}


note : #[bindings] supports

  • KV
  • D1
  • Vars
  • Service
  • Queue (producer)
  • Durable Objects

in cuurent version, as worker crate does. ( worker supports secrets, but secrets aren’t written in wrangler.toml… )


tips :

  • You can switch between multiple envs by feature flags like #[cfg_attr(feature = "...", bindings(env_name))]
  • For rust-analyzer user : when editting wrangler.toml around bindings, you’ll need to reload #[bindings] struct ...; to notice the new bindings to rust-analyer. For that, what you have to do is just deleting ; and immediate restoring it.