Sites without users
Contact form on a corporate site
access: 'visitor'@nuxtjs/turnstilenuxt-security
A mail-sending route that only your own pages can call, with a bot check and a rate limit.
A corporate site has no accounts, but its contact form route sends mail with your mail service's API key. Without protection, anyone can call it from any website or script and send mail in your name.
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@kurashina-design/nuxt-bff-guard', '@nuxtjs/turnstile', 'nuxt-security'],
bffGuard: { access: 'visitor' },
turnstile: { siteKey: process.env.NUXT_PUBLIC_TURNSTILE_SITE_KEY },
runtimeConfig: {
turnstile: { secretKey: '' }, // NUXT_TURNSTILE_SECRET_KEY
mailApiKey: '', // NUXT_MAIL_API_KEY
},
routeRules: {
'/api/contact': {
security: {
rateLimiter: { tokensPerInterval: 5, interval: 600_000 }, // 5 per 10 minutes per IP
requestSizeLimiter: { maxRequestSizeInBytes: 20_000 },
},
},
},
})
server/api/contact.post.ts
import { defineBffHandler } from '#bff-guard'
import { z } from 'zod'
const contactSchema = z.object({
name: z.string().min(1).max(100),
email: z.string().email(),
message: z.string().min(1).max(5000),
token: z.string(),
})
export default defineBffHandler(async (event) => {
const { token, ...contact } = await readValidatedBody(event, contactSchema.parse)
const check = await verifyTurnstileToken(token, event)
if (!check.success) throw createError({ statusCode: 400, statusMessage: 'Challenge failed' })
await $fetch('https://api.mail.example/send', {
method: 'POST',
headers: { authorization: `Bearer ${useRuntimeConfig(event).mailApiKey}` },
body: { to: 'info@example.com', replyTo: contact.email, subject: `Contact from ${contact.name}`, text: contact.message },
})
return { ok: true }
})
pages/contact.vue
<script setup lang="ts">
const form = reactive({ name: '', email: '', message: '', token: '' })
const sent = ref(false)
async function submit() {
await $fetch('/api/contact', { method: 'POST', body: form })
sent.value = true
}
</script>
<template>
<p v-if="sent">Thank you. We will reply soon.</p>
<form v-else @submit.prevent="submit">
<input v-model="form.name" required>
<input v-model="form.email" type="email" required>
<textarea v-model="form.message" required />
<NuxtTurnstile v-model="form.token" />
<button type="submit">Send</button>
</form>
</template>
Who stops what
| Attempt | Stopped by |
|---|---|
| A form or script on another website | the guard (403) |
curl without browser headers | the guard (403) |
| A script that copies the headers | Turnstile (400) |
| Many messages from one address | nuxt-security (429) |
| Huge payloads | nuxt-security (413) and the schema |