nuxt-modules / turnstile

๐Ÿ”ฅ Cloudflare Turnstile integration for Nuxt

Home Page:https://cloudflare.com/products/turnstile

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use it with noScripts flag enabled

marvincaspar opened this issue ยท comments

๐Ÿ“š What are you trying to do?

I'm building a static website with the current experimental feature noScripts. This is nice, because it gives so much performance. To execute the form submit I created a main.js file which contains the submit event handler. The main.js is rendered to the page via server plugin. This works fine.

How can I define that the specific turnstile component is allowed to execute the js stuff to render the cf captcha? Currently the form is rendered without the cf captcha and the request validation failed because there was no in the request body.

โ„น๏ธ Additional context

nuxt.config.ts

export default defineNuxtConfig({
  experimental: { noScripts: true },
  nitro: {
    prerender: {
      crawlLinks: true,
      routes: ['/'],
    },
  },
  modules: [
    'nuxt-turnstile',
  ],
  runtimeConfig: {
    turnstile: {
      secretKey: process.env.NUXT_TURNSTILE_SECRET_KEY || '',
    },
  },
  turnstile: {
    siteKey: '...',
  }
}

pages/contact.vue

<template>
  <div>
    <form onsubmit="onSubmit(event)">
      <label>Name<input type="text" name="name" /></label>
      <label>Message <textarea name="message"></textarea></label>
      <Turnstile name="token" :options="{ theme: 'light' }" />
      <button type="submit">Send!</button>
    </form>
  </div>
</template>

server/plugins/inject-js-script.ts:

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook(
    "render:html",
    (html: NuxtRenderHTMLContext, { event }) => {
      html.body.push('<script src="/main.js" defer></script>');
    }
  );
});

public/main.js

async function onSubmit(event) {
  event.preventDefault();

  const body = Object.fromEntries(new FormData(event.target).entries());

  const response = await $fetch('/api/contact', {
    method: 'POST',
    body: body,
  });

  console.log('RESPONSE', response);
}

Would you provide a reproduction so I can test this?

Hi, I invested some time in it and it seems to not work with disabling javascript because of the whole communication with cloudflare. So I will close this issue