Integration

Send email from Next.js with SNDR.

App Router, Pages Router, Server Actions and Route Handlers on the Node.js runtime. Typed email sending and signed webhooks.

Next.js is the framework most SNDR customers build on. The SDK provides ESM and CommonJS builds with TypeScript types. It uses fetch and Node crypto, so SDK routes must use the Node.js runtime. The recipes below cover the four patterns every Next.js codebase ends up needing — a Server Action that sends, a Route Handler that sends, a webhook receiver with signature verification, and a Node.js OTP endpoint.

Setup

Install + configure

Installbash
pnpm add @rkiza/sndr
# or
npm install @rkiza/sndr
# or
yarn add @rkiza/sndr
Environmentenv
# .env.local
SNDR_API_KEY=sndr_live_x9k2...
SNDR_WEBHOOK_SECRET=...   # only if you receive webhooks

Recipes

The patterns you actually need.

  1. Send from a Server Action (App Router)

    Server Actions are the cleanest way to send email from a form. The SDK runs in the Node runtime by default. Mark the action with 'use server' and you're done — Next handles the serialisation.

    // app/contact/actions.ts
    'use server';
    
    import { Sndr } from '@rkiza/sndr';
    import { z } from 'zod';
    
    const sndr = new Sndr(process.env.SNDR_API_KEY!);
    
    const contactSchema = z.object({
      name: z.string().min(2).max(120),
      email: z.string().email(),
      message: z.string().min(10).max(8000),
    });
    
    export async function sendContact(formData: FormData) {
      const input = contactSchema.parse({
        name: formData.get('name'),
        email: formData.get('email'),
        message: formData.get('message'),
      });
    
      await sndr.emails.send({
        from: 'hello@yourdomain.com',
        to: 'team@yourdomain.com',
        reply_to: input.email,
        subject: `New contact from ${input.name}`,
        text: input.message,
      });
    }
  2. Send from a Route Handler

    For non-form requests — e.g. a POST from another service or a scheduled job — use a Route Handler. The SDK auto-generates an Idempotency-Key per logical call and reuses it on retries, so a retry can replay the cached response.

    // app/api/welcome/route.ts
    import { NextResponse } from 'next/server';
    import { Sndr, SndrError } from '@rkiza/sndr';
    
    const sndr = new Sndr(process.env.SNDR_API_KEY!);
    
    export async function POST(req: Request) {
      const { email, name } = await req.json();
    
      try {
        const { id } = await sndr.emails.send({
          from: 'hello@yourdomain.com',
          to: email,
          subject: `Welcome, ${name}`,
          html: `<p>Thanks for joining us, ${name}.</p>`,
        });
        return NextResponse.json({ id });
      } catch (err) {
        if (err instanceof SndrError) {
          return NextResponse.json(
            { error: { code: err.code, message: err.message } },
            { status: (err.status >= 400 && err.status <= 599 ? err.status : 502) },
          );
        }
        throw err;
      }
    }
  3. Verify an incoming webhook

    When SNDR posts an event to your /api/webhooks/sndr endpoint, you need the raw body to verify the HMAC signature. Next.js's Route Handlers give you the raw stream directly — don't re-serialise.

    // app/api/webhooks/sndr/route.ts
    import { verifyWebhookSignature } from '@rkiza/sndr';
    import type { WebhookEventPayload } from '@rkiza/sndr';
    
    export async function POST(req: Request) {
      const raw = Buffer.from(await req.arrayBuffer());
      const ok = verifyWebhookSignature(
        raw,
        req.headers.get('x-sndr-signature') ?? '',
        process.env.SNDR_WEBHOOK_SECRET!,
      );
      if (!ok) return new Response('bad signature', { status: 400 });
    
      const event: WebhookEventPayload = JSON.parse(raw.toString('utf8'));
    
      switch (event.type) {
        case 'email.delivered':
          // event.data is typed as { email_id, to: string[] }
          console.log('delivered', event.data.email_id);
          break;
        case 'email.bounced':
          console.log('bounced', event.data.email_id, event.data.error);
          break;
        case 'email.unsubscribed':
          console.log('unsub', event.data.addresses);
          break;
      }
    
      return new Response('ok');
    }
  4. Send from a Node.js Route Handler

    Set the runtime export to 'nodejs'. The SDK imports node:crypto, which is unavailable in the Next.js Edge runtime. Use the HTTP API directly if the route must run on Edge.

    // app/api/otp/route.ts
    import { NextResponse } from 'next/server';
    import { Sndr } from '@rkiza/sndr';
    
    export const runtime = 'nodejs';
    const sndr = new Sndr(process.env.SNDR_API_KEY!);
    
    export async function POST(req: Request) {
      const { email } = await req.json();
      const code = String(Math.floor(100000 + Math.random() * 900000));
    
      await sndr.emails.send({
        from: 'auth@yourdomain.com',
        to: email,
        subject: `Your sign-in code: ${code}`,
        text: `Your code is ${code}. It expires in 10 minutes.`,
      });
    
      // ...persist code with TTL...
      return NextResponse.json({ ok: true });
    }
  5. Send a magic link

    Use a Node.js Route Handler and a securely generated tokenised URL. To deduplicate separate submissions, pass the same application-generated idempotencyKey for the same operation; SDK-generated keys only cover retries within one call.

    // app/api/magic-link/route.ts
    import { Sndr } from '@rkiza/sndr';
    import { randomBytes } from 'node:crypto';
    
    const sndr = new Sndr(process.env.SNDR_API_KEY!);
    
    export async function POST(req: Request) {
      const { email } = await req.json();
      const token = randomBytes(32).toString('hex');
      // ...persist token → email with 15-min TTL...
    
      const link = `https://yourdomain.com/auth/callback?token=${token}`;
    
      await sndr.emails.send({
        from: 'auth@yourdomain.com',
        to: email,
        subject: 'Sign in to yourdomain',
        html: `<p><a href="${link}">Click here to sign in</a>. Link expires in 15 minutes.</p>`,
      });
    
      return new Response('check your email');
    }

Next.js FAQ

Does the SDK work in the Edge runtime?
Use export const runtime = "nodejs" for SDK routes. The package imports node:crypto. For the Next.js Edge runtime, call the HTTP API with fetch instead.
How do I keep the API key out of client bundles?
Never instantiate the Sndr client in a Client Component or anywhere the bundle ships to the browser. Use Server Actions, Route Handlers, or middleware — all of which run server-side and never expose process.env.SNDR_API_KEY to the client.
What about the Pages Router?
Identical SDK, just a different surface. Instantiate Sndr at module scope inside pages/api/<route>.ts and call sndr.emails.send from the handler.
How do I avoid double-sending on retries?
The SDK auto-generates a UUID Idempotency-Key per logical send and reuses it across retries. You can override with a stable key from your domain (e.g. order id) by passing idempotencyKey in RequestOptions.
How do I test webhook delivery locally?
Tunnel localhost with ngrok or cloudflared, register the public URL as a webhook endpoint in the SNDR dashboard, then trigger sends. The dashboard shows every delivery attempt with the response code and body — debug failures end-to-end without a redeploy.

Send your first Next.js email.

3,000 emails a month on the Free plan. No credit card needed.