Send emails with Next.js

Integrate YourSend into your Next.js application using API routes.

Prerequisites

1. Install

npm install yoursend

Add your API key to .env.local:

.env.local
YOURSEND_API_KEY=ys_live_...

2. Create an API route

Create a server-side API route to send emails securely:

app/api/send/route.ts
import { YourSend } from 'yoursend';
import { NextResponse } from 'next/server';

const ys = new YourSend(process.env.YOURSEND_API_KEY!);

export async function POST(request: Request) {
  const { to, subject, html } = await request.json();

  const { data, error } = await ys.send({
    channel: 'email',
    from: 'hello@yourdomain.com',
    to,
    subject,
    html,
  });

  if (error) {
    return NextResponse.json({ error }, { status: 400 });
  }

  return NextResponse.json({ message_id: data.message_id });
}

3. Call from the client

app/contact/page.tsx
'use client';

async function sendEmail() {
  const res = await fetch('/api/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      to: 'user@example.com',
      subject: 'Hello from Next.js',
      html: '<p>This email was sent from a Next.js app!</p>',
    }),
  });
  const data = await res.json();
  console.log(data);
}

export default function ContactPage() {
  return <button onClick={sendEmail}>Send Email</button>;
}