Implementing Resend in Next.js: Step-by-Step Guide

Adrián Bailador - Jul 25 - - Dev Community

If you've ever needed to integrate an email sending system into your Next.js application, you're in the right place! In this guide, we'll explore how to do it efficiently using the Resend platform. I'll walk you through each step, from initial setup to best practices for production deployment. Let's get started!

1. Project Setup

First, make sure your Next.js application is ready. If you haven't created one yet, no worries—here's how to do it:

npx create-next-app my-email-app
cd my-email-app
Enter fullscreen mode Exit fullscreen mode

Install the necessary dependencies, including Resend:

npm install resend
Enter fullscreen mode Exit fullscreen mode

2. Configuring Resend

To use Resend, you'll need an account and an API key. Sign up at Resend and get your API key. Then, create a .env.local file at the root of your project and store your key there:

RESEND_API_KEY=your_api_key
Enter fullscreen mode Exit fullscreen mode

API Key Security

It's super important to keep your API key secure! Make sure this .env.local file is included in your .gitignore to prevent it from being uploaded to public repositories. Additionally, limit the permissions of the API key from your Resend account, allowing only what is necessary to reduce risks.

3. Creating the API for Sending Emails

Now let's create an API that will handle sending emails. Create a folder api/send inside app and a file route.ts:

import { Resend } from 'resend';
import { EmailTemplate } from '@/components/Email-template';
import { NextRequest, NextResponse } from 'next/server';

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: NextRequest) {
    if (req.method !== 'POST') {
        return NextResponse.json({ message: 'Method not allowed' }, { status: 405 });
    }

    try {
        const body = await req.json();
        const { name, surname, email } = body;

        const response = await resend.emails.send({
            to: email,
            from: 'no-reply@adrian.com',
            subject: 'Wedding of Adrian and Ana - Welcome! 🎉',
            react: EmailTemplate({ firstName: name, lastName: surname, email }),
        });

        return NextResponse.json({ message: 'Email sent', response }, { status: 200 });
    } catch (error) {
        console.error('Error sending email:', error);
        return NextResponse.json({ message: 'Error sending email', error }, { status: 500 });
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Creating the Email Template Component

To customise our emails, we'll create an email template. In the components folder, create the file Email-template.tsx:

interface EmailTemplateProps {
    firstName: string;
    lastName: string;
    email: string;
}

export const EmailTemplate: React.FC<Readonly<EmailTemplateProps>> = (
    {
        firstName,
        lastName,
        email
    }
) => (
    <div>
        <h1>Welcome, {firstName} {lastName}!</h1>
        <p>
            You have successfully signed up for our newsletter. You will receive our latest updates at {email}.
        </p>
        <a href="https://victoralvarado.dev" target="_blank" rel="noreferrer">
            Visit our website
        </a>
    </div>
);
Enter fullscreen mode Exit fullscreen mode

5. Email Sending Function

Now, we'll create a function to use our API for sending emails. In the api/emails folder, create sendEmail.ts:

interface Values {
    name: string;
    surname: string;
    email: string;
}

export const sendEmail = async (values: Values) => {
    try {
        const response = await fetch('/api/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(values),
        });

        if (response.ok) {
            console.log('Email sent successfully!');
        } else {
            const errorDetails = await response.json();
            console.error('Error sending email:', errorDetails.message);
        }
    } catch (error) {
        console.error('There was a problem sending the email:', error);
    }
};
Enter fullscreen mode Exit fullscreen mode

6. Additional Links and Resources

To delve deeper, here are some useful resources:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player