LogoMkSaaS Docs

Captcha

Learn how to set up and use captcha in MkSaaS

MkSaaS supports using Cloudflare Turnstile as a captcha service. This allows you to protect your website from spam and abuse.

Setup

To enable captcha, you need to configure the following environment variables in your .env file:

.env
NEXT_PUBLIC_TURNSTILE_SITE_KEY=""
TURNSTILE_SECRET_KEY=""
  1. Log in to the Cloudflare dashboard and select your account.
  2. Go to Turnstile.
  3. Select Add widget and fill out the site name and your website's hostname or select from your existing websites on Cloudflare.
  4. Select the widget mode to Managed.
  5. (Optional) Opt in for pre-clearance support.
  6. Copy your Site Key and Secret Key and paste it into your .env file as NEXT_PUBLIC_TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY.

Cloudflare Turnstile

For more details, see the Cloudflare Turnstile Documentation and React Turnstile Documentation.

If you are setting up the environment, now you can go back to the Environment Setup guide and continue. The rest of this guide can be read later.

Environment Setup

Set up environment variables


Captcha System Structure

captcha.tsx
captcha.ts
  • components/shared/captcha.tsx: The captcha component.
  • lib/captcha.ts: The captcha library for validating the captcha.

Usage

The captcha component is only used in the register form for now, but you can use it in other places as well.

src/components/auth/register-form.tsx
import { Captcha } from '@/components/shared/captcha';

export default function RegisterForm() {
  // ...

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)}>
        {/* ... */}
        <Captcha
            onSuccess={(token) => form.setValue('captchaToken', token)}
            validationError={form.formState.errors.captchaToken?.message}
          />
          <Button
            disabled={isPending || (turnstileEnabled && !captchaToken)}
            size="lg"
            type="submit"
            className="cursor-pointer w-full flex items-center justify-center gap-2"
          >
            {isPending && <Loader2Icon className="mr-2 size-4 animate-spin" />}
            <span>{t('signUp')}</span>
          </Button>
        </form>
    </Form>
  );
}

Reference

Next Steps

Now that you understand how to work with notifications in MkSaaS, explore these related integrations: