Nuxt.js
Integrate the vue google recaptcha with Nuxt.js
Install the required package using your preferred package manager:
npm install @google-recaptcha/vue
pnpm add @google-recaptcha/vue
yarn add @google-recaptcha/vue
bun add @google-recaptcha/vue
This package provides Vue components and composables for client-side reCAPTCHA integration.
Create a Nuxt plugin to initialize reCAPTCHA:
import { googleReCaptcha } from '@google-recaptcha/vue'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(googleReCaptcha, {
type: 'v3',
siteKey: 'your_site_key'
})
})
<template>
<form @submit.prevent="onSubmit">
...
<button type="submit">Submit</button>
</form>
</template>
<script setup>
import { useGoogleReCaptcha } from '@google-recaptcha/vue'
const googleReCaptcha = useGoogleReCaptcha()
const onSubmit = async () => {
const token = await googleReCaptcha.executeV3('action')
...
}
</script>
Optimize script loading
You can optimize performance by pre-loading the reCAPTCHA script using Nuxt's useHead
composable combined with the core utility function. The googleReCaptcha
plugin automatically detects if the reCAPTCHA script is already loaded and will not add a duplicate script tag.
import { googleReCaptcha } from '@google-recaptcha/vue';
import { generateGoogleReCaptchaScriptSrc } from '@google-recaptcha/core';
export default defineNuxtPlugin((nuxtApp) => {
const scriptSrc = generateGoogleReCaptchaScriptSrc({
isEnterprise: false,
render: 'your_site_key',
hl: 'en'
});
useHead({
script: [
{
src: scriptSrc,
async: true,
defer: true
}
]
});
nuxtApp.vueApp.use(googleReCaptcha, {
type: 'v3',
siteKey: 'your_site_key'
});
});
Last updated on