Skip to main content

Vercel Functions Integration

Learn how to send emails from Vercel Functions using Lettr.

Prerequisites

  • Vercel account
  • Node.js project
  • Lettr API key

Installation

Install the Lettr SDK:
npm install lettr

API Route (App Router)

Create a file at app/api/send/route.ts:
import { NextResponse } from 'next/server';
import { Lettr } from 'lettr';

const lettr = new Lettr(process.env.LETTR_API_KEY!);

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

    await lettr.emails.send({
      from: 'you@example.com',
      to: [to],
      subject,
      html
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { error: error.message },
      { status: 500 }
    );
  }
}

API Route (Pages Router)

Create a file at pages/api/send.ts:
import type { NextApiRequest, NextApiResponse } from 'next';
import { Lettr } from 'lettr';

const lettr = new Lettr(process.env.LETTR_API_KEY!);

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { to, subject, html } = req.body;

    await lettr.emails.send({
      from: 'you@example.com',
      to: [to],
      subject,
      html
    });

    res.status(200).json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

Edge Runtime

For faster cold starts, use the Edge runtime:
import { Lettr } from 'lettr';

export const runtime = 'edge';

const lettr = new Lettr(process.env.LETTR_API_KEY!);

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

  await lettr.emails.send({
    from: 'you@example.com',
    to: [to],
    subject,
    html
  });

  return Response.json({ success: true });
}

Environment Variables

Add your API key in the Vercel dashboard or via CLI:
vercel env add LETTR_API_KEY
Or in your .env.local for development:
LETTR_API_KEY=your-api-key

Server Actions (Next.js 14+)

'use server';

import { Lettr } from 'lettr';

const lettr = new Lettr(process.env.LETTR_API_KEY!);

export async function sendEmail(formData: FormData) {
  const to = formData.get('email') as string;
  const subject = formData.get('subject') as string;
  const message = formData.get('message') as string;

  await lettr.emails.send({
    from: 'you@example.com',
    to: [to],
    subject,
    html: `<p>${message}</p>`
  });

  return { success: true };
}