Integrating Nuxt 3 with Google reCAPTCHA v2

NottDev
4 min readOct 2, 2024

--

To create a plugin for Google reCAPTCHA v2 in Nuxt 3, follow these steps:

Step 1: Get Your reCAPTCHA v2 Site Key

  1. Go to the reCAPTCHA Enterprise console or to the reCAPTCHA console.
  2. dsdRegister your site, and choose reCAPTCHA v2
  3. Get the site key (you’ll need this for configuring the plugin)

Step 2: Create a Nuxt 3 Plugin for reCAPTCHA v2

In Nuxt 3, plugins are typically created in the plugins directory. You will write a plugin that loads the Google reCAPTCHA v2 script and allows you to interact with it within your application.

  1. Create the Plugin File:
    Inside the plugins directory, create a new file named google-reCAPTCHA-v2.client.js. This will ensure that the plugin only runs on the client side (since reCAPTCHA is client-side).
mkdir -p plugins
touch plugins/google-reCAPTCHA-v2.client.js

2. Add the reCAPTCHA Loader to the Plugin:

export default defineNuxtPlugin(() => {
const siteKey = 'YOUR_RECAPTCHA_SITE_KEY' // Replace with your site key

// Function to dynamically load the reCAPTCHA script
function loadRecaptchaScript() {
return new Promise((resolve, reject) => {
// Check if the script is already present
if (document.getElementById('recaptcha-script')) {
return resolve(window.grecaptcha) // reCAPTCHA is already loaded
}

// Create the script tag for reCAPTCHA
const script = document.createElement('script')
script.id = 'recaptcha-script'
script.src = 'https://www.google.com/recaptcha/api.js?render=explicit' // Explicit rendering
script.async = true
script.defer = true

script.onload = () => {
if (window.grecaptcha) {
resolve(window.grecaptcha) // Resolve the promise with grecaptcha when loaded
} else {
reject(new Error('reCAPTCHA failed to load.'))
}
}

script.onerror = () => reject(new Error('Failed to load reCAPTCHA script.'))

document.head.appendChild(script) // Add the script to the document
})
}

// Initialize the reCAPTCHA
loadRecaptchaScript()
.then((grecaptcha) => {
console.log('reCAPTCHA script loaded.')

// Provide a function to use reCAPTCHA
nuxtApp.provide('recaptcha', {
render: (elementId, callback) => {
grecaptcha.ready(() => {
grecaptcha.render(elementId, {
sitekey: siteKey,
callback,
})
})
},
execute: (action, callback) => {
grecaptcha.ready(() => {
grecaptcha.execute(siteKey, { action }).then((token) => {
callback(token)
})
})
},
})
})
.catch((error) => {
console.error('Error loading reCAPTCHA:', error)
})
})

Step 3: Use reCAPTCHA v2 in Your Components or Pages

Now that the reCAPTCHA plugin is set up, you can use it in any component or page by accessing it via the $recaptcha method.

Example: Using reCAPTCHA v2 with a Form:

Inside your component (e.g., components/ContactForm.vue), you can integrate reCAPTCHA like this:

<template>
<form @submit.prevent="submitForm">
<!-- Your form fields -->
<div class="form-group">
<input type="text" v-model="name" placeholder="Name" required />
</div>
<div class="form-group">
<input type="email" v-model="email" placeholder="Email" required />
</div>

<!-- The reCAPTCHA widget -->
<div id="recaptcha-widget"></div>

<button type="submit">Submit</button>
</form>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useNuxtApp } from '#app'

const { $recaptcha } = useNuxtApp()

const name = ref('')
const email = ref('')

const submitForm = () => {
// You can access your form data here before reCAPTCHA verification
console.log('Submitting form:', { name: name.value, email: email.value })

// Trigger reCAPTCHA and handle token
$recaptcha.execute('submit', (token: string) => {
console.log('reCAPTCHA token:', token)
// Now you can submit the form data along with the token to your backend
})
}

onMounted(() => {
// Render reCAPTCHA on component mount
$recaptcha.render('recaptcha-widget', (response: string) => {
console.log('reCAPTCHA completed:', response)
})
})
</script>

Step 4: Add Styling (Optional)

You can style the reCAPTCHA widget as needed. Typically, the reCAPTCHA widget is responsive, but you can modify the CSS if required.

Explanation:

  • Plugin Initialization: The plugin loads the Google reCAPTCHA v2 script and provides two key methods:
  • render: To render the reCAPTCHA widget on a specific element.
  • execute: To execute the reCAPTCHA (e.g., for invisible reCAPTCHA or explicitly triggered verification).
  • Use in Components: In the component, the reCAPTCHA widget is rendered within a specific div using the render method, and the execute method is used to validate the user’s response when the form is submitted.
  • Token Handling: After the user completes reCAPTCHA, you get a token which you can send to your backend for validation.

Step 5: Backend Validation (Optional)

After receiving the reCAPTCHA token in your component, you should send it to your backend to verify it using Google’s reCAPTCHA API:

POST https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={recaptchaToken}

Include the secretKey and your recaptchaToken in the request.

Request to verify the response token

--

--

NottDev
NottDev

Written by NottDev

Your only limit is your mind.

No responses yet