Image

nuxtjs

Recaptcha

Setup recaptcha.

1 min read
Last update: November 28, 2021

For Laravel backend installation, check Laravel reCAPTCHA

Dependencies

yarn add @nuxtjs/recaptcha
  • Add this to nuxt.config.js with config with dotenv module
nuxt.config.js
export default {
    modules: [
        '@nuxtjs/recaptcha',
    ],
    recaptcha: {
        hideBadge: true,
        siteKey: process.env.RECAPTCHA_SITE_KEY,
        version: 3,
        size: 'invisible',
    },
}
.env
RECAPTCHA_SITE_KEY=

Form

Create form component

components/contact-form.vue
<template>
  <div>
    <form @submit.prevent="sumbit">
      <div>
        <label for="name"> Name </label>
        <input
          id="name"
          v-model="form.name"
          type="text"
          name="name"
          autocomplete="name"
          required
        />
      </div>
      <div>
        <label for="email"> Email </label>
        <input
          id="email"
          v-model="form.email"
          name="email"
          type="email"
          autocomplete="email"
          required
        />
      </div>
      <div>
        <label
          for="message"
        >
          Message
        </label>
        <textarea
          id="message"
          v-model="form.message"
          name="message"
          rows="4"
          required
        ></textarea>
      </div>
      <div>
        <button type="submit">Send</button>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'ContactForm',
  data() {
    return {
      form: {
        name: '',
        email: '',
        message: '',
      },
    }
  },
  async mounted() {
    try {
      await this.$recaptcha.init()
    } catch (e) {
      console.error(e)
    }
  },
  beforeDestroy() {
    this.$recaptcha.destroy()
  },
  methods: {
    async sumbit() {
      try {
        const token = await this.$recaptcha.execute('login')
        this.form['g-recaptcha-response'] = token

        await this.$axios.post('/submission', this.form)

        this.form = {
          name: '',
          email: '',
          message: '',
        }
      } catch (e) {}
    },
  },
}
</script>