A form action runs on the server, so the API key stays private and the form works even before JavaScript loads.
Environment
# .env
ROBUSTEMAIL_API_KEY=rb_test_...
The form action
// src/routes/contact/+page.server.ts
import { fail } from "@sveltejs/kit";
import { env } from "$env/dynamic/private";
import type { Actions } from "./$types";
export const actions = {
default: async ({ request, fetch }) => {
const data = await request.formData();
const email = String(data.get("email") ?? "");
const message = String(data.get("message") ?? "");
if (!email.includes("@") || !message) {
return fail(400, { email, message, error: "Please enter your email and a message." });
}
const res = await fetch("https://robustemail.com/api/v2/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${env.ROBUSTEMAIL_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "Acme Website <website@acme.com>",
to: "team@acme.com",
reply_to: email,
subject: "New contact form message",
text: message,
}),
});
if (!res.ok) {
const body = await res.json();
console.error("Email failed", body.name, body.message);
return fail(502, { email, message, error: "We could not send your message. Please try again." });
}
return { success: true };
},
} satisfies Actions;
The page
<!-- src/routes/contact/+page.svelte -->
<script lang="ts">
import { enhance } from "$app/forms";
let { form } = $props();
</script>
{#if form?.success}
<p>Thanks, we will reply soon.</p>
{:else}
<form method="POST" use:enhance>
<input name="email" type="email" value={form?.email ?? ""} required />
<textarea name="message" required>{form?.message ?? ""}</textarea>
{#if form?.error}<p>{form.error}</p>{/if}
<button>Send</button>
</form>
{/if}