> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lettr.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Vercel Functions

> Send transactional emails from Vercel serverless functions using Lettr's HTTP API in Next.js API routes and server actions.

Send transactional emails from Vercel serverless functions using Lettr's HTTP API. Vercel's global edge network and fast cold starts make it perfect for email-triggered API routes and server actions.

Using Cursor? [Jump straight in using this prompt](https://cursor.com/link/prompt?text=Help%20me%20add%20a%20Lettr%20sending%20example%20for%20Vercel%20Functions%2C%20or%20migrate%20my%20current%20Vercel%20email%20sending%20solution%20to%20Lettr%20using%20these%20docs%3A%20https%3A%2F%2Fdocs.lettr.com%2Fquickstart%2Fserverless%2Fvercel-quickstart)

## Prerequisites

Before you begin, make sure you have:

<CardGroup cols={2}>
  <Card title="API Key" icon="key" href="https://app.lettr.com/api-keys">
    Create an API key in the Lettr dashboard
  </Card>

  <Card title="Verified Domain" icon="globe" href="/learn/domains/sending-domains">
    Add and verify your sending domain
  </Card>
</CardGroup>

You'll also need:

* **Vercel account** with a project deployed or ready to deploy
* **Next.js project** (recommended) or a Node.js serverless function
* **Node.js 18.x or 20.x** runtime

## Quick Setup

<Steps>
  <Step title="Install the Lettr SDK">
    ```bash theme={null}
    npm install lettr
    ```

    The SDK provides a clean interface for sending emails with full TypeScript support.
  </Step>

  <Step title="Add environment variables">
    Add your API key via the Vercel dashboard or CLI:

    ```bash theme={null}
    vercel env add LETTR_API_KEY
    ```

    When prompted, paste your API key (starts with `lttr_`). Then add your from email:

    ```bash theme={null}
    vercel env add FROM_EMAIL
    ```

    <Tip>
      For local development, create a `.env.local` file with the same variables. Vercel automatically loads `.env.local` in development mode.
    </Tip>
  </Step>

  <Step title="Create an API route">
    Create a file at `app/api/send/route.ts` (App Router) or `pages/api/send.ts` (Pages Router) with the code examples below.
  </Step>

  <Step title="Deploy">
    ```bash theme={null}
    vercel deploy
    ```

    Your email API route will be available at `https://your-domain.vercel.app/api/send`.
  </Step>
</Steps>

## Next.js App Router (Recommended)

For Next.js 13+ projects using the App Router, create a file at `app/api/send/route.ts`:

```typescript theme={null}
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 body = await request.json();
    const { to, subject, html, text } = body;

    // Validate required fields
    if (!to || !subject || (!html && !text)) {
      return NextResponse.json(
        { error: 'Missing required fields: to, subject, and html or text' },
        { status: 400 }
      );
    }

    // Send email via Lettr
    const result = await lettr.emails.send({
      from: process.env.FROM_EMAIL || 'noreply@yourdomain.com',
      to: Array.isArray(to) ? to : [to],
      subject,
      html,
      text,
    });

    console.log(`Email sent successfully. Request ID: ${result.request_id}`);

    return NextResponse.json({
      success: true,
      requestId: result.request_id,
      accepted: result.accepted,
    });
  } catch (error: any) {
    console.error('Failed to send email:', error);

    return NextResponse.json(
      { error: error.message || 'Failed to send email' },
      { status: error.status || 500 }
    );
  }
}

// Configure function execution
export const maxDuration = 30; // Max duration in seconds (Pro plan and higher)
```

<Info>
  The `maxDuration` export configures the maximum execution time for the function. Email sending typically completes in under 1 second, but setting a higher limit accounts for retries and network latency.
</Info>

## Next.js Pages Router

For Next.js projects using the Pages Router, create a file at `pages/api/send.ts`:

```typescript theme={null}
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
) {
  // Only allow POST requests
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

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

    // Validate required fields
    if (!to || !subject || (!html && !text)) {
      return res.status(400).json({
        error: 'Missing required fields: to, subject, and html or text',
      });
    }

    // Send email
    const result = await lettr.emails.send({
      from: process.env.FROM_EMAIL || 'noreply@yourdomain.com',
      to: Array.isArray(to) ? to : [to],
      subject,
      html,
      text,
    });

    console.log(`Email sent. Request ID: ${result.request_id}`);

    res.status(200).json({
      success: true,
      requestId: result.request_id,
      accepted: result.accepted,
    });
  } catch (error: any) {
    console.error('Email send failed:', error);

    res.status(error.status || 500).json({
      error: error.message || 'Internal server error',
    });
  }
}

// Configure function execution
export const config = {
  maxDuration: 30,
};
```

## What's Next

<CardGroup cols={2}>
  <Card title="Advanced Guide" icon="book-open" href="/quickstart/serverless/vercel-advanced">
    Learn about Server Actions, Edge Runtime, and advanced patterns
  </Card>

  <Card title="AWS Lambda" icon="aws" href="/quickstart/serverless/aws-lambda-quickstart">
    Deploy on AWS Lambda
  </Card>

  <Card title="Cloudflare Workers" icon="cloudflare" href="/quickstart/serverless/cloudflare-quickstart">
    Deploy on Cloudflare
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/emails/send-email">
    Complete API documentation
  </Card>
</CardGroup>
