Recipe: Send email from a Next.js Server Action

Call Notify from a Next.js App Router Server Action — keep the API key on the server.

Server Actions run on the server, so they are a good place for NOTIFY_API_KEY.

// app/actions/sendWelcome.ts
'use server';

export async function sendWelcomeEmail(to: string) {
  const response = await fetch('https://notify.cx/api/email/send', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': process.env.NOTIFY_API_KEY!
    },
    body: JSON.stringify({
      to,
      subject: 'Welcome',
      message: '<p>Thanks for signing up.</p>',
      from: 'noreply@your-verified-domain.com'
    })
  });

  if (!response.ok) {
    throw new Error(await response.text());
  }
}

Call from a form:

<form action={async (fd) => {
  'use server';
  await sendWelcomeEmail(String(fd.get('email')));
}}>
  <input name="email" type="email" required />
  <button type="submit">Send</button>
</form>

Never import the API key into Client Components.

Where to next?