Dyrected
Guides

Handling Form Submissions

Learn how to build contact forms, lead captures, and waitlists using Dyrected collections.

Dyrected makes it easy to capture user input from your frontend. Instead of setting up a separate backend or using a service like Formspree, you can save form submissions directly into a Dyrected collection.

1. Create a Submissions Collection

First, define a collection in your dyrected.config.ts to store the data. The key is setting the create access to true (or a function that returns true) so that anyone can submit the form.

// dyrected.config.ts
import { defineConfig } from '@dyrected/core'

export default defineConfig({
  collections: [
    {
      slug: 'contact-requests',
      access: {
        read: ({ req }) => req.user?.role === 'admin', // Only admins can read
        create: () => true,                            // Anyone can create
      },
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'email', type: 'email', required: true },
        { name: 'message', type: 'textarea', required: true },
      ],
    },
  ],
})

The easiest way to submit data is using the .create() method on your collection.

import { createClient } from '@dyrected/sdk'

const client = createClient({
  baseUrl: 'https://your-site.com/api',
  siteId: '...' // Required for Cloud mode
})

async function handleSubmit(data) {
  try {
    const result = await client.collection('contact-requests').create({
      name: data.name,
      email: data.email,
      message: data.message,
    })
    console.log('Success:', result)
  } catch (err) {
    console.error('Submission failed:', err.message)
  }
}

Next.js & Nuxt Wrappers

If you are using the Next.js or Nuxt packages, you can use the built-in hooks:

// Next.js example
import { useDyrected } from '@dyrected/next'

const client = useDyrected()
await client.collection('contact-requests').create(data)

3. Using the REST API

If you aren't using the SDK, you can send a standard POST request to your collection endpoint.

const response = await fetch('https://your-site.com/api/collections/contact-requests', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-site-id': 'your-site-id' // Required for Cloud mode
  },
  body: JSON.stringify({
    name: 'Jane Doe',
    email: '[email protected]',
    message: 'Hello from the frontend!'
  })
})

const result = await response.json()

4. Managing Submissions

Once submitted, your data appears instantly in the Dyrected Admin.

  • Permissions: Ensure your read access is restricted to admins so user data stays private.
  • Validation: Dyrected automatically validates the data against your schema before saving it. If the email is invalid or a required field is missing, you'll get a 400 Bad Request with details.
  • Emails: You can use the hooks feature in your collection to send an email notification whenever a new submission is created.

On this page