Hapi CAPTCHA Integration
This recipe shows how to integrate TrustCaptcha into a Hapi application. The frontend setup is the same as for any other Node.js application — this page focuses on the server-side validation.
The setup section gets you to a working integration in three small steps using a route handler directly. Below it, an optional refactor section shows the more reusable Hapi-idiomatic approach (a route extension implemented as a Hapi plugin).
Preparation
Section titled “Preparation”You should have already completed the following steps before you wire TrustCaptcha into your Hapi 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 Hapi route receives in request.payload 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 Node.js SDK
Section titled “2. Install the Node.js SDK”npm i @hapi/hapi @trustcomponent/trustcaptcha-nodejs@^3.0.03. Validate the token in your route handler
Section titled “3. Validate the token in your route handler”import Hapi from "@hapi/hapi";import { TrustCaptcha } from "@trustcomponent/trustcaptcha-nodejs";
const server = Hapi.server({ host: "localhost", port: 8080 });
server.route({ method: "POST", path: "/contact", handler: async (request, h) => { // In production, load from env: process.env.TRUSTCAPTCHA_API_KEY const apiKey = "<your_api_key>"; const payload = request.payload as Record<string, string>; const token = payload["tc-verification-token"] ?? "";
try { const result = await TrustCaptcha.getVerificationResult(apiKey, token); if (!result.verificationPassed || result.score > 0.5) { return h.response("CAPTCHA verification failed.").code(400); } } catch (err) { return h.response("CAPTCHA verification failed.").code(400); }
// CAPTCHA passed — payload is safe to use. // ... your business logic ...
return "Thanks!"; },});
await server.start();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: extract to a route extension
Section titled “Refactor: extract to a route extension”If you protect more than one route, the most idiomatic Hapi approach is a pre extension that runs before the handler. The verification call then becomes a single pre entry on every protected route.
Configure the API key
Section titled “Configure the API key”TRUSTCAPTCHA_API_KEY=<your_api_key>Create the pre-handler
Section titled “Create the pre-handler”import type { Request, ResponseToolkit } from "@hapi/hapi";import { TrustCaptcha } from "@trustcomponent/trustcaptcha-nodejs";
export async function verifyTrustCaptcha(request: Request, h: ResponseToolkit) { const payload = request.payload as Record<string, string> | undefined; const token = payload?.["tc-verification-token"] ?? ""; if (!token) { return h.response("CAPTCHA verification failed.").code(400).takeover(); }
try { const result = await TrustCaptcha.getVerificationResult( process.env.TRUSTCAPTCHA_API_KEY!, token, ); if (!result.verificationPassed || result.score > 0.5) { return h.response("CAPTCHA verification failed.").code(400).takeover(); } } catch (err) { return h.response("CAPTCHA verification failed.").code(400).takeover(); }
return h.continue;}h.response(...).takeover() short-circuits the request — Hapi sends the response directly and skips the route handler. Returning h.continue lets the handler run normally.
Apply the pre-handler to your routes
Section titled “Apply the pre-handler to your routes”import { verifyTrustCaptcha } from "./captcha";
server.route({ method: "POST", path: "/contact", options: { pre: [{ method: verifyTrustCaptcha }], handler: async (request, h) => { // CAPTCHA already verified — payload is safe to use. return "Thanks!"; }, },});For multiple routes, define the same pre entry on each, or extract a route options object and reuse it.
Payload parser. Hapi parses application/x-www-form-urlencoded and application/json automatically — request.payload is the parsed object. No extra plugin needed.
Joi validation. If you use @hapi/joi (or joi) to validate the payload, declare tc-verification-token in the schema (or set unknown(true)) so it isn’t stripped before the pre-handler runs.
Singleton SDK instance. For configured usage (custom timeouts, proxy, custom API host), construct a single TrustCaptcha instance once at startup with new TrustCaptcha({ apiKey, ... }) and reach it via server.app.trustCaptcha = ... — read it inside the pre-handler from request.server.app.trustCaptcha. See the Node.js Guide for the constructor options.
Next steps
Section titled “Next steps”Once you have wired TrustCaptcha into your Hapi 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.