Skip to main content

Guides

SvelteKit form actions

Wire a contact form to Postboi with a one-line SvelteKit action.


postboi/kit reads FormData, sends it, and returns { success: true } — or fail(400, { error }) on failure. A contact-form action is a single line.

// +page.server.ts
import { send } from 'postboi/kit';

export const actions = { default: send };
// +page.server.ts
import { send } from 'postboi/kit';

export const actions = { default: send };

The form

Point a multipart/form-data form at the action. Field names use the fieldset→field syntax to group related fields, and _subject (and friends) set the email’s special fields.

<!-- +page.svelte -->
<script lang="ts">
	import { enhance } from '$app/forms';
</script>

<form method="POST" use:enhance enctype="multipart/form-data">
	<input type="hidden" name="_subject" value="Contact Form" />
	<input name="contact→name" placeholder="Name" required />
	<input name="contact→email" type="email" placeholder="Email" required />
	<textarea name="details→message" placeholder="Message"></textarea>
	<input type="file" name="details→attachments" multiple />
	<button type="submit">Send</button>
</form>
<!-- +page.svelte -->
<script lang="ts">
	import { enhance } from '$app/forms';
</script>

<form method="POST" use:enhance enctype="multipart/form-data">
	<input type="hidden" name="_subject" value="Contact Form" />
	<input name="contact→name" placeholder="Name" required />
	<input name="contact→email" type="email" placeholder="Email" required />
	<textarea name="details→message" placeholder="Message"></textarea>
	<input type="file" name="details→attachments" multiple />
	<button type="submit">Send</button>
</form>

The submitted FormData becomes a tidy HTML table in the email body. See FormData for how the table is built.

Using a configured instance

Got a configured provider instance (or no ambient env vars)? Wrap it with action(). You can pass status for the failure code and fields for defaults merged into every send.

import Resend from 'postboi/resend';
import { action } from 'postboi/kit';
import { RESEND_API_KEY, EMAIL_FROM_ADDRESS } from '$env/static/private';

const mail = new Resend({ api_key: RESEND_API_KEY, default: { from: EMAIL_FROM_ADDRESS } });

export const actions = {
	default: action(mail, { status: 422, fields: { to: 'team@example.com' } })
};
import Resend from 'postboi/resend';
import { action } from 'postboi/kit';
import { RESEND_API_KEY, EMAIL_FROM_ADDRESS } from '$env/static/private';

const mail = new Resend({ api_key: RESEND_API_KEY, default: { from: EMAIL_FROM_ADDRESS } });

export const actions = {
	default: action(mail, { status: 422, fields: { to: 'team@example.com' } })
};