Search code examples
javascriptvue.jsrecaptcha

How to use google recaptcha in nuxt?


I am using nuxt and would like to use this library: https://github.com/nuxt-community/recaptcha-module. But I don't understand how to verify that the user has passed the check. The example doesn't tell me too much (https://github.com/nuxt-community/recaptcha-module/blob/master/example/v3/pages/index.vue). Could someone show me how to do it correctly?


Solution

  • This example is only half the story. It returns a Recaptcha V3 token on the client-side.

    This must then be sent to the serverside and verified using your secret key.

    This is done by sending a post to this URL:

    const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${token}`;
    

    You do not want to allow this secret key on the client side.

    To achieve this in Nuxt, assuming version 2.13+, you can utilise privateRuntimeConfig in your nuxt config.

    This will allow you to link a .env file to be injected only on the server side.

    For this use case, a privateRuntimeConfig like this should suffice:

    privateRuntimeConfig: {
        secretKey: process.env.GOOGLE_SECRET
    }
    

    Once you have done this, you will be able to access these variables as part of this.$config within your Nuxt application - in this case this.$config.secretKey when calling the Recaptcha verify endpoint.

    For more information check out the Nuxt blog