How to Protect Your React App from Bots with hCaptcha

Vojtěch Jedlička
Stackademic
Published in
3 min readApr 30, 2022

--

Robot beats captcha.

Protecting from bots, or “hackers” can be a difficult task. Thankfully Captcha saves the day! This weekend I made an app out of boredom and addiction to programming, that allowed my friends and me to easily share / store text, or some files. I realized, that having a free connection to my Firestore database wasn’t really a good idea and I needed some way to limit uploads. I needed solid bot protection — my friends are familiar with programming and could “pen test it”, but any app should have this kind of protection when dealing with user content storage.

Captcha is the way

I immediately knew I would use a captcha, but which one? I learned about reCaptcha and while Googling (how ironic) I found out about hCaptcha which wasn’t from Google, so I chose it. hCaptcha provides its classification data to multiple companies and you get rewarded with some tokens you can donate to charity, or use image classification services yourself.

How does it work?

I had the audacity to steal a nice diagram from hCaptcha docs site, but it should be similar to any Captcha service.

Captcha validation flow

Explain, please?

It’s really simple. When user completes the captcha, he receives a token from the captcha service. The token is proof, that it (probably) is a human. Having only client know about this is useless. Your server needs to know, so you pass the token along your protected request. On the server, you have to check its validity. This is simple — you just ask the service “is this a valid token?” and the service replies.

Implementation in Next.js

Let’s start with dependencies.

yarn add @hcaptcha/react-hcaptcha

There is also a library called next-hcaptcha for Next.js, but I had to implement my own middleware, due to some implementation details.

Captcha.tsx

Custom Captcha component

The usage of this component is straightforward. You display it and wait for the token. Once you have it, add it to the request headers. You can use g-recaptcha-response or h-captcha-response

Next.js middleware for captcha token validity checking

Captcha middleware validator for Next.js

If you are not familiar with middleware you can check the documentation for Next.js or Express.

But TLDR: you “wrap” your API route with this function. Such as

Secrets, Environmental variables

I forgot to mention, that you will need a hCaptcha service API key — the secret. You can find it after logging in to hCaptcha. You can also see some weird keys like 0x0000000000000000000000000000000000000000 based on the current environment. Those are used for local testing. You can find the documentation here.

Hope you liked it :)

Thank you for reading until the end. Please consider following the writer and this publication. Visit Stackademic to find out more about how we are democratizing free programming education around the world.

--

--