Nuxt reCAPTCHA Module
repository·main·Indexed 42 days ago
https://github.com/nuxt-community/recaptcha-moduleA Google reCAPTCHA integration for Nuxt.js supporting v2, v3, and Enterprise mode. Version 1.1.2 provides a ReCaptcha class API with methods for initialization, execution, and token retrieval, along with a dedicated Vue component for v2 implementations.
What's inside Nuxt reCAPTCHA
- When sending a token from the client to your server, you must verify it on the server side to ensure the request is not from a bot. The verification process is the same for both v2 and v3. Refer to the server middleware examples in the repository for implementation details.
Install and Setup @nuxtjs/recaptcha
mainTo integrate Google reCAPTCHA into your Nuxt.js project, follow these steps:
- Install the dependency:
npm install @nuxtjs/recaptcha
or
yarn add @nuxtjs/recaptcha
2. Add the module to your `nuxt.config.js`. You can either pass options directly within the `modules` array or use a top-level `recaptcha` configuration object. ```js // Option 1: Inline configuration { modules: [ ['@nuxtjs/recaptcha', { /* reCAPTCHA options */ }] ] } // Option 2: Top-level configuration { modules: ['@nuxtjs/recaptcha'], recaptcha: { /* reCAPTCHA options */ } }- Install the dependency:
Hide reCAPTCHA Badges
mainYou are permitted to hide the reCAPTCHA badge (for v3 or v2 with
size: 'invisible') provided that you include the reCAPTCHA branding in the user flow.Example requirement:
<small>This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply. </small>Use reCAPTCHA v3
mainFor reCAPTCHA v3, you must initialize the service and execute it for specific actions.
- Call
await this.$recaptcha.init()inside themountedhook. - Call
await this.$recaptcha.execute('action_name')inside your submit handler to get the token. - Call
this.$recaptcha.destroy()inside thebeforeDestroyhook to clean up scripts, styles, and the badge.
// In your component async mounted() { try { await this.$recaptcha.init() } catch (e) { console.error(e); } } async onSubmit() { try { const token = await this.$recaptcha.execute('login') // send token to server } catch (error) { console.log('Login error:', error) } } beforeDestroy() { this.$recaptcha.destroy() }- Call
Use reCAPTCHA v2
mainFor reCAPTCHA v2, use the
<recaptcha>component within your form and use the$recaptchahelper to retrieve the token.- Place the
<recaptcha />component inside your form. - In your submit handler, call
await this.$recaptcha.getResponse()to get the token. - Important: Call
await this.$recaptcha.reset()after the submission is complete to reset the widget.
<template> <form @submit.prevent="onSubmit"> <input v-model="email" type="email"> <recaptcha /> <button type="submit">Sign In</button> </form> </template> <script> export default { async onSubmit() { try { const token = await this.$recaptcha.getResponse() // send token to server await this.$recaptcha.reset() } catch (error) { console.log('Login error:', error) } } } </script>- Place the
Configure @nuxtjs/recaptcha options
mainThe
recaptchaconfiguration object accepts the following keys:Key Type Description siteKeyStringSite key for requests versionNumberreCAPTCHA version modeStringMode: 'base'or'enterprise'sizeStringSize for v2: 'compact','normal', or'invisible'languageStringRecaptcha language (v2 only) hideBadgeBooleanHide badge element (v3 or v2 via size: 'invisible')Configure reCAPTCHA using Runtime Config
mainTo securely use environment variables for your
siteKey, define it withinpublicRuntimeConfigin yournuxt.config.js.// nuxt.config.js export default { publicRuntimeConfig: { recaptcha: { siteKey: process.env.RECAPTCHA_SITE_KEY } } }Configure the ReCaptcha instance
mainThe
ReCaptchaclass is instantiated with an options object. These options are typically provided via your Nuxt configuration.Configuration Options
Option Description siteKeyRequired. Your Google reCAPTCHA site key. versionRequired. The reCAPTCHA version (e.g., 2or3).modeSet to 'enterprise'to use the Google reCAPTCHA Enterprise API.sizeThe size of the widget (e.g., 'invisible').languageThe language code for the reCAPTCHA widget (e.g., 'en').hideBadgeIf true, attempts to hide the reCAPTCHA badge via CSS.Note on
hideBadge:- For v3, the badge is set to
display: none. - For v2, the badge is set to
visibility: hidden. Usingdisplay: noneon v2 may disable spam checking functionality.
// Example configuration object passed to the constructor const options = { siteKey: 'YOUR_SITE_KEY', version: 3, mode: 'enterprise', hideBadge: true, language: 'en' };- For v3, the badge is set to
Configure the @nuxtjs/recaptcha module
mainThe
@nuxtjs/recaptchamodule is configured within yournuxt.config.jsfile. Options provided in therecaptchakey innuxt.config.jswill be merged with the module's default options. The module automatically registers a plugin (recaptcha.js) and a Vue component template (recaptcha.vue) to make reCAPTCHA functionality available throughout your Nuxt application.export default { modules: [ '@nuxtjs/recaptcha' ], recaptcha: { // Your configuration options here } }Use the ReCaptcha class API
mainThe
ReCaptchaclass is injected into the Nuxt context and provides methods to manage the reCAPTCHA lifecycle, execute challenges, and handle responses.Core Methods
init(): Initializes the reCAPTCHA script and returns a Promise that resolves when the script is loaded and ready.execute(action): (reCAPTCHA v3) Executes a reCAPTCHA v3 action. Returns a Promise that resolves with the token.getResponse(widgetId): Retrieves the response token for a specific widget. For invisible reCAPTCHA, it triggers the execution.reset(widgetId): Resets the reCAPTCHA widget. For v2, this is required to allow the user to try again after a failure.render(reference, { sitekey, theme }): Manually renders a reCAPTCHA widget on a specific DOM element or Vue component instance.destroy(): Cleans up the reCAPTCHA instance by removing the script, styles, and the badge from the DOM.on(event, callback): Subscribes to reCAPTCHA lifecycle events via an internal event bus.
Events
recaptcha-success: Emitted when a token is successfully retrieved.recaptcha-error: Emitted when an error occurs during execution.recaptcha-expired: Emitted when the reCAPTCHA token expires.
// Example usage of the injected recaptcha instance // 1. Execute a v3 action const token = await this.$recaptcha.execute('login'); // 2. Listen for success/error events this.$recaptcha.on('recaptcha-success', (token) => { console.log('Success:', token); }); this.$recaptcha.on('recaptcha-error', (error) => { console.error('Error:', error); }); // 3. Reset a v2 widget this.$recaptcha.reset(widgetId);