#Best way to add google recaptcha
1 messages · Page 1 of 1 (latest)
Hi @meager pendant. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Nuxt 3, the best way to add Google reCAPTCHA depends on whether you are using a dedicated integration like Firebase or a standard implementation. Here are the recommended approaches based on the available documentation:
1. Configure Keys in runtimeConfig
Regardless of the method you choose, you should store your site keys in the nuxt.config.ts. This allows you to update them via environment variables without rebuilding your app [Is Nuxt 3's runtimeConfig UNSAFE?].
export default defineNuxtConfig({
runtimeConfig: {
// Secret keys (server-side only)
reCaptchaSecretKey: '',
public: {
// Public keys (accessible on client)
reCaptchaSiteKey: process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY,
}
}
})
2. Standard Implementation (Nuxt Scripts)
The most performant way to load third-party scripts like Google reCAPTCHA is using the Nuxt Scripts module (@nuxt/scripts). It provides a useScript composable that ensures the script is loaded safely and can be triggered only when needed (e.g., when a user interacts with a form), which improves your performance metrics [Loading Third Party Assets with Nuxt Scripts].
Alternatively, for a simple manual integration, you can use useHead in your component:
<script setup>
useHead({
script: [
{
src: `<https://www.google.com/recaptcha/api.js?render=${useRuntimeConfig(>).public.reCaptchaSiteKey}`,
async: true,
defer: true
}
]
})
</script>
3. Using with Firebase (VueFire)
If you are using Firebase, the nuxt-vuefire module has built-in support for reCAPTCHA Enterprise through App Check [How to use Nuxt VueFire Session Cookie].
// nuxt.config.ts
export default defineNuxtConfig({
vuefire: {
appCheck: {
debug: process.env.NODE_ENV !== "production",
isTokenAutoRefreshEnabled: true,
provider: "ReCaptchaEnterprise",
key: process.env.NUXT_PUBLIC_GCP_RECAPTCHA_ENTERPRISE_SITE_KEY,
},
},
})
Important Security Considerations
- Keep Secrets Secret: Never place your reCAPTCHA "Secret Key" inside the
publicobject of yourruntimeConfig. It must only be used on the server side (e.g., in a Nitro server route) to verify the user's token [Is Nuxt 3's runtimeConfig UNSAFE?]. - Domain Restrictions: In your Google Cloud/reCAPTCHA console, ensure you restrict your API keys to your specific domains (e.g.,
yourdomain.com). Note that during local development on SSR, you might encounter referer errors if the server doesn't send a matching header, so ensurelocalhostis also allowed in your dev environment [How to use Nuxt VueFire Session Cookie]. - Content Security Policy (CSP): If you use a strict CSP, you may need to allow Google's domains for scripts and frames to prevent the reCAPTCHA from being blocked [Support CSP for Nuxt as static SPA].