hCaptcha on a Supabase Login Page: Site Key in the Browser, Secret in Supabase
Stop scripts guessing passwords on a Next.js login page: switch on Supabase attack protection with hCaptcha, keep the secret in Supabase and the site key in the front end, and pass the widget's single-use token to signInWithPassword.
What you will learn
- Explain how a captcha stops brute-force password guessing on a login form
- Turn on Captcha protection in Supabase and get a site key and secret from hCaptcha
- Add the hCaptcha widget to a React login form and send its token with signInWithPassword
- Reset the widget after a failed sign-in, because tokens work only once
Before you start
- Email login with Supabase in Next.js
- React useState and useRef
When you build fast with vibe coding, think about security early, and the login page is where attacks start. Picture a script that tries one password after another on our login form, thousands of times. That's a brute-force attack, and a plain login form can't tell a script from a person.
A captcha adds one small check before the sign-in: the "I am human" box. A person ticks it in a second. A script gets stopped right there, and because every try needs a fresh captcha, nobody can keep guessing passwords.
This builds on the starter kit's email login.
Two keys, two homes
hCaptcha gives you a site key and a secret. The site key goes in the front end. It tells the widget which site it belongs to, and it's safe in the browser. When the person ticks the box, the widget hands you a token. The login action sends that token to Supabase with the email and password, and Supabase checks it with hCaptcha using the secret. So the secret stays in Supabase only.
Step 1: switch it on in Supabase
Authentication → Attack Protection → Enable Captcha protection. There are two providers: hCaptcha and Turnstile by Cloudflare. If you already use Cloudflare, say for your DNS, Turnstile is a good choice too. We'll use hCaptcha. The Captcha secret field is empty for now.
Step 2: get the keys from hCaptcha
- On hcaptcha.com, open Pricing. The Basic plan is free. Click Get Started, skip the Pro offers, and sign up.
- On the dashboard, open Sites → Add Site and give it a name. Each site has its own site key.
- The domain field rejects localhost ("please enter a valid domain"). That's fine: the domain is optional, so leave it empty while you work locally.
- Open Onboarding → Generate Secret, and copy it now. hCaptcha shows it only once.
Back in Supabase, paste the secret into the Captcha secret field and save. From now on, Supabase asks for a captcha token whenever someone signs in with a password.
Step 3: the widget, via a prompt
Role: A Next.js developer on our admin starter kit.
Context: hCaptcha protection is on in Supabase, and the secret is saved there.
Task: Put the hCaptcha widget on the login page, send its token with the sign-in, and add the site key entry to sample.env.
Format: Change only the files you need, and list each one with a line on why.
The agent touched three files: the login form, the login action, and sample.env.
The login form
From components/auth/login-form.tsx, the captcha parts only:
import HCaptcha from "@hcaptcha/react-hcaptcha";
const HCAPTCHA_SITE_KEY = process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY;
export function LoginForm({
redirectTo = "/dashboard",
initialError,
}: {
redirectTo?: string;
initialError?: string;
}) {
const [state, formAction] = useActionState<AuthState, FormData>(login, {
error: initialError,
});
const captchaRef = useRef<HCaptcha>(null);
const [captchaToken, setCaptchaToken] = useState("");
// hCaptcha tokens are single-use. After a failed submit the server returns a
// fresh error, so clear the spent token and reset the widget for a retry.
useEffect(() => {
if (state.error) {
setCaptchaToken("");
captchaRef.current?.resetCaptcha();
}
}, [state.error]);
// ...email and password fields...
{/* Bot protection. The token is verified by Supabase on sign-in. */}
<input type="hidden" name="captchaToken" value={captchaToken} />
{HCAPTCHA_SITE_KEY ? (
<HCaptcha
ref={captchaRef}
sitekey={HCAPTCHA_SITE_KEY}
onVerify={(token) => setCaptchaToken(token)}
onExpire={() => setCaptchaToken("")}
onError={() => setCaptchaToken("")}
/>
) : (
<p className="text-[13px] text-danger">
Captcha is not configured. Set NEXT_PUBLIC_HCAPTCHA_SITE_KEY in your
environment.
</p>
)}
<SubmitButton disabled={!captchaToken}>Sign in</SubmitButton>
- The widget gets the site key and a
ref, so the form can reset it later. onVerifystores the token incaptchaToken.onExpireandonErrorclear it.- The token rides in a hidden input named
captchaToken, so it's sent with the form. - Sign in stays disabled while there's no token. The submit button got a small
disabledoption for exactly this. - The
useEffectat the top resets the widget after any error, because a token works only once.
The login action
export async function login(_prev: AuthState, formData: FormData): Promise<AuthState> {
const email = String(formData.get("email") ?? "").trim();
const password = String(formData.get("password") ?? "");
const captchaToken = String(formData.get("captchaToken") ?? "");
const redirectTo = String(formData.get("redirectTo") ?? "/dashboard") || "/dashboard";
if (!email || !password) {
return { error: "Enter your email and password." };
}
if (!captchaToken) {
return { error: "Please complete the captcha." };
}
const supabase = await createClient();
const { error } = await supabase.auth.signInWithPassword({
email,
password,
options: { captchaToken },
});
if (error) return { error: error.message };
revalidatePath("/", "layout");
redirect(redirectTo);
}
Supabase checks that token with hCaptcha, using the secret we saved. Our code never sees the secret.
The env entry
sample.env gets one new line, NEXT_PUBLIC_HCAPTCHA_SITE_KEY. Its comment points out that hCaptcha publishes a test site key that always passes, which is handy for local testing. Copy the entry into your own .env, then replace the test value with your real site key from the hCaptcha Sites page. Only the site key goes in this file.
Run it
In the Frontend folder run npm install (it said "up to date", since the hCaptcha package was already in place) and npm run dev. On the login page:
- Sign in is greyed out from the start.
- The widget shows "I am human", plus a warning that localhost was detected. That's expected on localhost, and the check still works.
- Type the email and password: still disabled. Tick the box, hCaptcha runs its check, Sign in turns on. Click it, and you're on the dashboard.
- Get the password wrong, and the form shows the error and resets the widget, so Sign in is disabled until you tick again.
Continue with Google doesn't need the box, because that sign-in happens on Google's own page (see Google sign-in with Supabase).
Common mistakes
- Putting the secret in
.env. The front end only ever needs the site key. - Reusing a token after a failed sign-in. Tokens are single-use. Reset the widget.
- Forgetting the test key is still in place. It always passes, so it protects nothing in production.
- Leaving sign-up unprotected. Once Captcha protection is on, add the widget to every password form you have.
Quick recap
| Piece | Where it lives |
|---|---|
| Captcha protection switch | Supabase, Authentication, Attack Protection |
| Secret | Supabase only |
| Site key | NEXT_PUBLIC_HCAPTCHA_SITE_KEY in .env |
| Token | Widget onVerify, hidden input, options: { captchaToken } |
| Retry | resetCaptcha() after every error |
Try it yourself
Add the same widget to the sign-up page, or prompt your coding agent to do it, and then read every line it gives you. Check that supabase.auth.signUp gets the token in its options too.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Server State With TanStack Query: One Key, One Request, One Cache
Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.
Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.
