{}

Submit JSON with Nuxt

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.


Set up your Nuxt project

  1. To get started, make sure you have a working Nuxt project. If yo do not, follow these instructions.
  2. Next, install submitjson, vee-validate, zod, and @vee-validate/zod with your favorite package manager.
pnpm add submitjson vee-validate zod @vee-validate/zod
shell
  1. Copy your API key and save it to your environment. Then configure your nuxt.config.ts like so. This approach protects your api key 💂🏻
export default defineNuxtConfig({
  runtimeConfig: {
    submitJsonApiKey: process.env.NUXT_SUBMIT_JSON_API_KEY
  }
})
nuxt.config.ts

Create a Nuxt Server Route

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
})
server/api/submit.ts

Create a Submission Component

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>
ReportForm.vue

Integrate in your pages

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>
pages/report.vue

🚛✨💚 Nice job, you successfully integrated Submit JSON with Nuxt.