Submit JSON is not only for contact us form notifications. In this example we're going to build a notification when one of your users reports an innapropriate post or comment on your website.
submitjson
, vee-validate
, zod
, and @vee-validate/zod
with your favorite package manager.pnpm add submitjson vee-validate zod @vee-validate/zod
nuxt.config.ts
like so. This approach protects your api key 💂🏻export default defineNuxtConfig({
runtimeConfig: {
submitJsonApiKey: process.env.NUXT_SUBMIT_JSON_API_KEY
}
})
After updating your config, create a server route at /server/api/submit.ts
, import submitjson
, and set up the event handler to handle a submission.
import SubmitJSON from 'submitjson'
export default defineEventHandler(async (event) => {
const { submitJsonApiKey } = useRuntimeConfig(event)
const sj = new SubmitJSON({ apiKey: submitJsonApiKey, endpoint: 'xxx' })
const body = await readBody(event)
const submission = await sj.submit(body) // optionally configure options
return submission
})
Now that the server route is configured, create a ReportForm.vue
component. This example uses vee-valide
and zod
to validate the form automatically before submission.
<script setup lang="ts">
import { Form, Field } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import * as zod from 'zod'
// create the validation schema for the form
const schema = toTypedSchema(
zod.object({
reason: zod.string().min(1),
details: zod.string().optional(),
}),
)
async function onSubmit(values: any) {
// submit the report to the server route we made earlier
await useFetch('/api/submit', { method: 'POST', body: values})
}
</script>
<template>
<Form @submit="onSubmit">
<Field name="reason" as="select">
<option>Bad attitude</option>
<option>Trolling</option>
<option>Other</option>
</Field>
<Field name="details" as="textarea" />
<button type="submit">Submit Report</button>
</Form>
</template>
Finally, use the <ReportForm />
component with your pages and other components
<script setup lang="ts">
useSeoMeta({
title: 'Report Comments with Submit JSON',
})
</script>
<template>
<ReportForm />
</template>
🚛✨💚 Nice job, you successfully integrated Submit JSON with Nuxt.