Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • Running a Next.js Admin Starter Kit: Route Groups, Theme Tokens and npm run dev
  • Remotion Basics: A Video as One Composition Object, Frames, Sequences and the Player
  • Spline: Put a 3D Scene on a Landing Page Without Writing 3D Code
  • Framer: A Launch Page Without Code, From a Free Animated Template
  • Three.js: What It Can Do on Real Sites, and How to Let Your AI Agent Use It
  • Animated Component Libraries (Magic UI, Aceternity UI): Copy-In Motion and When It Becomes Noise
  • WebGPU and Three.js Shaders in TSL: A Living Gradient, 4,500 Particles and a Hover Ripple
  • Deploy Many Vite Demos as One Static Site: A Gallery Page, One Build Command and import.meta.env.BASE_URL
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Finishing a Remotion Video Editor: Timeline Sync, Track Order, Trims and Fades, and the Server MP4 Render
  • A 3D Product Page in React and Three.js: Scroll Becomes a Number, One Camera Shot per Panel, One Choice Drives Everything
  • A Personal 3D Portfolio Room in React Three Fiber: Hover Glow, Click to Open, Pointer Drift and a Contact Form to FastAPI
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  • Supabase as a Backend: Postgres, Instant APIs, Row Level Security and the Two Keys
  • Email Login With Supabase in Next.js: Three Clients, Server Actions, the Callback Route and Middleware
  • Google Sign-In With Supabase in Next.js: Which Address Goes Where
  • hCaptcha on a Supabase Login Page: Site Key in the Browser, Secret in Supabase
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Working with APIs

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

Captcha token flow Login page widget + site key (public) tick: token Supabase gets email, password and the token holds the secret hCaptcha checks the token with the secret pass: signed in. fail: sign-in refused.
The site key is public. The secret never leaves the Supabase dashboard.

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

  1. On hcaptcha.com, open Pricing. The Basic plan is free. Click Get Started, skip the Pro offers, and sign up.
  2. On the dashboard, open Sites → Add Site and give it a name. Each site has its own site key.
  3. 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.
  4. 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.
  • onVerify stores the token in captchaToken. onExpire and onError clear 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 disabled option for exactly this.
  • The useEffect at 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

PieceWhere it lives
Captcha protection switchSupabase, Authentication, Attack Protection
SecretSupabase only
Site keyNEXT_PUBLIC_HCAPTCHA_SITE_KEY in .env
TokenWidget onVerify, hidden input, options: { captchaToken }
RetryresetCaptcha() 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 75 of 75

Previous
Google Sign-In With Supabase in Next.js: Which Address Goes Where

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.

On this page

  • Two keys, two homes
  • Step 1: switch it on in Supabase
  • Step 2: get the keys from hCaptcha
  • Step 3: the widget, via a prompt
  • The login form
  • The login action
  • The env entry
  • Run it
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.