Contents: Next.js
Next.js
Use a client component that sends the form with fetch, so visitors stay on the page and see a success message right away.
1. Add your key
NEXT_PUBLIC_FORMIZ_KEY=fmz_your_key_here
2. Create the form component
'use client';
import { useState, type FormEvent } from 'react';
type Status = 'idle' | 'sending' | 'sent' | 'error';
export default function ContactForm() {
const [status, setStatus] = useState<Status>('idle');
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setStatus('sending');
const data = new FormData(event.currentTarget);
data.append('access_key', process.env.NEXT_PUBLIC_FORMIZ_KEY!);
const res = await fetch('https://api.formiz.app/submit', {
method: 'POST',
body: data,
});
setStatus(res.ok ? 'sent' : 'error');
}
return (
<form onSubmit={handleSubmit}>
<input name="name" required />
<input name="email" type="email" required />
<textarea name="message" required />
<button disabled={status === 'sending'}>Send</button>
{status === 'sent' && <p>Thanks! Your message is on its way.</p>}
{status === 'error' && <p>Something went wrong. Please try again.</p>}
</form>
);
}3. Use it on a page
import ContactForm from './ContactForm';
export default function ContactPage() {
return (
<main>
<h1>Contact us</h1>
<ContactForm />
</main>
);
}Variables that start with NEXT_PUBLIC_ are visible in the browser. That is fine for an access key, but restrict it to your domain in Settings so it only works on your site.
Keeping the key on the server
Prefer the key never to reach the browser? Send the form from a server action instead and store the key in a variable without the NEXT_PUBLIC_ prefix.
'use server';
export async function sendContact(formData: FormData) {
formData.append('access_key', process.env.FORMIZ_KEY!);
const res = await fetch('https://api.formiz.app/submit', {
method: 'POST',
body: formData,
});
return { ok: res.ok };
}