Setting Up Google reCAPTCHA in Nuxt 3

1. Get reCAPTCHA API Keys

Before integrating reCAPTCHA into your Nuxt 3 project, you need API keys from Google. Go to Google reCAPTCHA Admin, Register a new site and select reCAPTCHA v3. Then, Add your domain (for production) or localhost (for development). Copy the Site Key and Secret Key.

2. Install vue-recaptcha-v3 To integrate reCAPTCHA, install the vue-recaptcha-v3 package:

npm install vue-recaptcha-v3

3. Configure reCAPTCHA in Nuxt 3 Add Plugin for reCAPTCHA by Creating a new plugin file plugins/google-recaptcha.js in your Nuxt 3 project:

// plugins/google-recaptcha.js
import { defineNuxtPlugin } from "#app";
import { VueReCaptcha } from 'vue-recaptcha-v3';


export default defineNuxtPlugin((nuxtApp) => {
    const config = useRuntimeConfig();
    nuxtApp.vueApp.use(VueReCaptcha, {
        siteKey: config.public.CAPTCHA_SITEKEY, // add your sitekey here
    });
});

Create a new composables file composables/useGlobalRecaptcha.ts in your Nuxt 3 project:

// composables/useGlobalRecaptcha.ts
import { useReCaptcha } from 'vue-recaptcha-v3';

export const useGlobalRecaptcha = () => {
    const recaptchaInstance = useReCaptcha();

    const getRecaptchaToken = async (action: string) => {
        await recaptchaInstance?.recaptchaLoaded();
        const token = await recaptchaInstance?.executeRecaptcha(action);
        return token;
    };

    return {
        getRecaptchaToken,
    };
};

3. Use reCAPTCHA in a Component

Example: Protecting a Form Submission

Edit your component (e.g., components/MyForm.vue):


<script setup>
const { getRecaptchaToken } = useGlobalRecaptcha();


const onSubmit = async () => {
      const captcha_token = await getRecaptchaToken("yourActionHere");
  const { data, error } = await useFetch('/api/verify-recaptcha', {
    method: '',
    body: { 
        captcha_token: captcha_token
    }
  });

  if (error.value) {
    console.error('reCAPTCHA validation failed:', error.value);
  } else {
    console.log('Form submitted successfully:', data.value);
  }
};
</script>

<template>
  <form @submit.prevent="onSubmit">
    <button type="submit">Submit</button>
  </form>
</template>
Deployment Considerations

Ensure your reCAPTCHA keys are set correctly in your environment.

Use separate keys for development and production.

Monitor reCAPTCHA scores to prevent false positives.