Cloudflare Worker written in Rust to create an hCaptcha verification endpoint.
To learn how to code this up from scratch in Rust using wrangler, see the article on using Rust in serverless Cloudflare workers. If you have any questions, please drop a comment at the bottom of that page.
If you would like to use the Worker read on!
You will need a Cloudflare account as well as an hCaptcha account. Both services have a free tier.
-
Start by cloning this repo:
git clone https://github.com/rodneylab/hcaptcha-serverless-rust-worker cd hcaptcha-serverless-rust-worker
-
Continue by setting up a Cloudflare account if you do not yet have one.
-
Now create an hCaptcha account, if you don't yet have one.
-
If you do not yet have a Rust development environment set up on your machine, head over to the official Rust site for the recommended one-line terminal command to get that up and running.
-
Install the wrangler tool on your machine:
cargo install wrangler
-
Next link your Cloudflare account to your local environment:
wrangler login
-
Now we will define some variables. Start with your hCaptcha site key (get this from the hCaptcha dashboard):
wrangler secret put HCAPTCHA_SITEKEY
paste in your site key when prompted.
-
Repeat with your hCaptcha secret key
wrangler secret put HCAPTCHA_SECRETKEY
-
Finally we will define the CORS origins. This is a comma separated list of valid domains you want to be able to send requests from (typically your live client site and a local development site). If you have the the following domains:
Enter the secret as
https://www.example.com,http://127.0.0.1:3000
when prompted.Let's define this now then:
wrangler secret put CORS_ORIGIN
That should be everything set up.
-
Now fire up the dev server for testing:
wrangler dev
By default the worker will be available locally at
http://127.0.0.1:8787
. -
Now you need to generate an hCaptcha request from a client app and send it to
http://127.0.0.1:8787/verify
as JSON, using thePOST
method. If you are working in JavaScript, you might code this up something like this:
async function handleVerify() {
try {
if (browser) {
const { response } = await hcaptcha.execute(hcaptchaWidgetID, {
async: true,
});
const responsePromise = fetch(`${workerUrl}/verify`, {
method: 'POST',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
response,
}),
});
}
} catch (error) {
console.error(`Error in handleVerify: ${error}`);
}
}