Actix Web CAPTCHA Integration
This recipe shows how to integrate TrustCaptcha into an Actix Web application. The frontend setup is the same as for any other web application — this page focuses on the server-side validation.
The setup section gets you to a working integration in three small steps using a handler function directly. Below it, an optional refactor section shows a more reusable approach: a shared TrustCaptcha instance via web::Data plus a small helper called from each protected handler.
Preparation
Section titled “Preparation”You should have already completed the following steps before you wire TrustCaptcha into your Actix Web application.
Read Get-Started: Get a quick overview of the concepts behind TrustCaptcha and the integration process in get started.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
1. Embed the frontend widget
Section titled “1. Embed the frontend widget”First, add the TrustCaptcha script to your page (see the JavaScript Guide for version pinning and self-hosting options).
Then place the <trustcaptcha-component> element inside your form. The widget appends a hidden tc-verification-token field on submit, which your Actix Web backend receives like any other form input.
<script type="module" src="https://cdn.trustcomponent.com/trustcaptcha/3.0.x/trustcaptcha.esm.min.js"></script>
<form method="post" action="/contact"> <label>Email</label> <input type="email" name="email" required>
<trustcaptcha-component sitekey="<your_site_key>"></trustcaptcha-component>
<button type="submit">Send</button></form>See the Widget Overview for the full property reference.
2. Install the Rust SDK
Section titled “2. Install the Rust SDK”cargo add trustcaptcha@^3.03. Validate the token in your handler
Section titled “3. Validate the token in your handler”use actix_web::{post, web, App, HttpResponse, HttpServer, Responder};use serde::Deserialize;use trustcaptcha::trust_captcha::TrustCaptcha;
#[derive(Deserialize)]struct ContactForm { email: String, #[serde(rename = "tc-verification-token")] tc_verification_token: String,}
#[post("/contact")]async fn submit(form: web::Form<ContactForm>) -> impl Responder { // In production, load from env: std::env::var("TRUSTCAPTCHA_API_KEY").unwrap() let api_key = "<your_api_key>";
let trust_captcha = match TrustCaptcha::builder(api_key).build() { Ok(tc) => tc, Err(_) => return HttpResponse::InternalServerError().body("CAPTCHA setup failed."), };
let result = match trust_captcha.get_verification_result(&form.tc_verification_token).await { Ok(result) => result, Err(_) => return HttpResponse::BadRequest().body("CAPTCHA verification failed."), };
if !result.verification_passed || result.score > 0.5 { return HttpResponse::BadRequest().body("CAPTCHA verification failed."); }
// CAPTCHA passed — request data is safe to use. // ... your business logic ...
HttpResponse::Ok().body("Thanks!")}
#[actix_web::main]async fn main() -> std::io::Result<()> { HttpServer::new(|| App::new().service(submit)) .bind("127.0.0.1:8080")? .run() .await}That’s it — the form is now protected. For real deployments, move the API key out of the source code (see the comment) and consider explicit failover handling — see Failover Behavior for the reasoning and a code template.
Refactor: share the SDK and extract a helper
Section titled “Refactor: share the SDK and extract a helper”If you protect more than one route, build the TrustCaptcha once at startup, share it via web::Data, and wrap the three lines of verification logic in a small helper. Each protected handler then needs a single verify_token(&trust_captcha, ...)? line — no copy/paste.
A custom Actix extractor would be even more elegant, but extractors that run before web::Form<...> only see request parts (headers, URI), not the form body — and the body has already been consumed by the time you’d want to read the token from it. A helper called from inside the handler keeps things straightforward and matches the <form method="post"> flow shown above.
Build the SDK once and inject it
Section titled “Build the SDK once and inject it”use actix_web::{web, App, HttpServer};use std::env;use trustcaptcha::trust_captcha::TrustCaptcha;
#[actix_web::main]async fn main() -> std::io::Result<()> { let api_key = env::var("TRUSTCAPTCHA_API_KEY").expect("TRUSTCAPTCHA_API_KEY missing"); let trust_captcha = web::Data::new( TrustCaptcha::builder(api_key).build().expect("TrustCaptcha build failed"), );
HttpServer::new(move || { App::new() .app_data(trust_captcha.clone()) .service(submit) }) .bind("127.0.0.1:8080")? .run() .await}Create the helper
Section titled “Create the helper”use actix_web::HttpResponse;use trustcaptcha::trust_captcha::TrustCaptcha;
/// Returns `Ok(())` if the CAPTCHA passed, otherwise an HTTP 400 response/// you can return directly from the handler with `?`.pub async fn verify_token( trust_captcha: &TrustCaptcha, token: &str,) -> Result<(), HttpResponse> { let result = trust_captcha .get_verification_result(token) .await .map_err(|_| HttpResponse::BadRequest().body("CAPTCHA verification failed."))?;
if !result.verification_passed || result.score > 0.5 { return Err(HttpResponse::BadRequest().body("CAPTCHA verification failed.")); }
Ok(())}Call the helper from your handlers
Section titled “Call the helper from your handlers”use actix_web::{post, web, HttpResponse, Responder};use crate::captcha::verify_token;
#[post("/contact")]async fn submit( trust_captcha: web::Data<TrustCaptcha>, form: web::Form<ContactForm>,) -> impl Responder { if let Err(response) = verify_token(&trust_captcha, &form.tc_verification_token).await { return response; }
// CAPTCHA passed — request data is safe to use. // ... your business logic ...
HttpResponse::Ok().body("Thanks!")}A single verify_token(...).await line per handler now opts the route into CAPTCHA verification.
Tokio runtime. The Rust SDK is async/reqwest-based — call .await from inside an async fn. Don’t block in synchronous contexts.
Sharing the SDK. A built TrustCaptcha is immutable and safe to share. Build it once at startup, wrap it in web::Data<…> and clone the handle for every handler — don’t rebuild it per request. For configured usage (custom timeouts, proxy, custom API host), pass them via the builder: TrustCaptcha::builder(api_key).api_host(...).proxy(...).build(). See the Rust Guide for the full builder API.
Next steps
Section titled “Next steps”Once you have wired TrustCaptcha into your Actix Web application, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:
Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.
Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.
Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.
Failover behavior: Decide how your backend should behave when our service is temporarily unreachable. This is particularly important for high-availability flows where blocking real users during an outage is worse than letting through a small amount of unverified traffic. Learn more about failover behavior.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.