Nuxt reCAPTCHA Module

repository·main·Indexed 42 days ago

https://github.com/nuxt-community/recaptcha-module

A 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.

Tokens
2.2K
Snippets
7
Records
10
Agent score
54%

What's inside Nuxt reCAPTCHA

  1. Verify reCAPTCHA tokens on the Server Side

    main
    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.
  2. Install and Setup @nuxtjs/recaptcha

    main

    To integrate Google reCAPTCHA into your Nuxt.js project, follow these steps:

    1. 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 */
      }
    }
  3. Hide reCAPTCHA Badges

    main

    You 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>
  4. Use reCAPTCHA v3

    main

    For reCAPTCHA v3, you must initialize the service and execute it for specific actions.

    1. Call await this.$recaptcha.init() inside the mounted hook.
    2. Call await this.$recaptcha.execute('action_name') inside your submit handler to get the token.
    3. Call this.$recaptcha.destroy() inside the beforeDestroy hook 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()
    }
  5. Use reCAPTCHA v2

    main

    For reCAPTCHA v2, use the <recaptcha> component within your form and use the $recaptcha helper to retrieve the token.

    1. Place the <recaptcha /> component inside your form.
    2. In your submit handler, call await this.$recaptcha.getResponse() to get the token.
    3. 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>
  6. Configure @nuxtjs/recaptcha options

    main

    The recaptcha configuration object accepts the following keys:

    KeyTypeDescription
    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')
  7. Configure the ReCaptcha instance

    main

    The ReCaptcha class is instantiated with an options object. These options are typically provided via your Nuxt configuration.

    Configuration Options

    OptionDescription
    siteKeyRequired. Your Google reCAPTCHA site key.
    versionRequired. The reCAPTCHA version (e.g., 2 or 3).
    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. Using display: none on 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'
    };
  8. Configure the @nuxtjs/recaptcha module

    main

    The @nuxtjs/recaptcha module is configured within your nuxt.config.js file. Options provided in the recaptcha key in nuxt.config.js will 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
      }
    }
  9. Use the ReCaptcha class API

    main

    The ReCaptcha class 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);