LogoStarterkitpro
Features/Emails

SendGrid

Switching from Resend to SendGrid for sending emails.

If you prefer to use SendGrid instead of the default Resend provider for sending emails, follow these steps. Note that @resend/react is still used for rendering email templates regardless of the sending provider.

1. Package Management

First, uninstall the resend sending package (if installed) and install the SendGrid package. Keep @resend/react for template rendering.

Terminal
npm uninstall resend
npm install @sendgrid/mail

2. Configuration Update (lib/app-config.ts)

Add a sendgrid configuration object to your lib/app-config.ts file. You can remove or comment out the resend object if you won't be using it for sending.

lib/app-config.ts (Additions)
export const appConfig = {
  // ... other configs
  sendgrid: {
    // Optional: Subdomain used for sending (matches DNS setup)
    subdomain: "mail", // Common SendGrid subdomain
    // Required: Sender for system emails (e.g., magic links)
    fromNoReply: `YourAppName <noreply@mail.yourdomain.com>`,
    // Required: Sender for other emails (e.g., marketing, updates)
    fromAdmin: `Your Name at YourAppName <yourname@mail.yourdomain.com>`,
    // Contact email for support replies
    supportEmail: "support@yourdomain.com",
  },
  // ... other configs
};

Critical Setup

Update fromNoReply, fromAdmin, and supportEmail with your actual domain and desired email addresses. The optional subdomain should match the domain/subdomain you verified in Sendgrid and configured in your DNS.

3. Replace Email Sending Helper (lib/sendgrid.ts)

If you have a lib/resend.ts specifically for sending emails, delete it:

Terminal
rm lib/resend.ts

Create a new file named lib/sendgrid.ts and add the following code to handle sending via SendGrid:

lib/sendgrid.ts (New File)
import React from "react";
import { render } from "@react-email/render"; // Use render from @react-email/render
import sgMail from "@sendgrid/mail";
import { appConfig } from "./app-config";
 
// Initialize SendGrid with API key
if (!process.env.AUTH_SENDGRID_KEY) {
  console.group("⚠️ AUTH_SENDGRID_KEY missing from .env");
  console.error("It's required to send emails via SendGrid.");
  console.error("If you don't need it, remove the code from /lib/sendgrid.ts");
  console.groupEnd();
} else {
  sgMail.setApiKey(process.env.AUTH_SENDGRID_KEY);
}
 
/**
 * Sends an email using SendGrid
 *
 * @async
 * @param {string | string[]} to - The recipient's email address(es)
 * @param {string} subject - The subject of the email
 * @param {string} html - The HTML content of the email
 * @param {string} [from] - Optional from email address (overrides default)
 * @param {string} [replyTo] - Optional reply-to email address
 * @returns {Promise<boolean>} A Promise that resolves to true if the email was sent successfully
 */
export async function sendEmail({
  to,
  subject,
  html,
  from = appConfig.sendgrid.fromNoReply, // Use sendgrid config
  replyTo = appConfig.sendgrid.supportEmail, // Default replyTo
}: {
  to: string | string[];
  subject: string;
  html: string;
  from?: string;
  replyTo?: string;
}): Promise<boolean> {
  if (!process.env.AUTH_SENDGRID_KEY) {
    console.error("SendGrid API key is missing. Cannot send email.");
    return false;
  }
 
  const msg = {
    to: Array.isArray(to) ? to : [to],
    from: from, // SendGrid uses 'from' directly
    replyTo: replyTo,
    subject: subject,
    html: html,
  };
 
  try {
    await sgMail.send(msg);
    console.log(`Email sent to ${Array.isArray(to) ? to.join(", ") : to}`);
    return true;
  } catch (error: any) {
    console.error("Error sending email via SendGrid:", error);
    if (error.response) {
      console.error(error.response.body);
    }
    return false;
  }
}
 
/**
 * Renders a React email component to HTML string
 *
 * @param Component The React component to render
 * @param props The props to pass to the component
 * @returns The rendered HTML string
 */
export function renderEmail<Props extends object>(
  Component: React.FunctionComponent<Props> | React.ComponentClass<Props>,
  props: Props
): string {
  // Use render from @react-email/render for synchronous rendering to string
  return render(React.createElement(Component, props));
}

4. Update Environment Variables

Update your .env.local file. Remove or comment out AUTH_RESEND_KEY and add your AUTH_SENDGRID_KEY:

.env.local
# Remove or comment out:
# AUTH_RESEND_KEY=re_xxxxxxxxxxxxxxxxxxxx
 
# Add:
AUTH_SENDGRID_KEY=SG.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

5. Update Authentication Provider (lib/auth/auth-config.ts)

Modify your NextAuth configuration in lib/auth/auth-config.ts to use the SendGrid provider for Magic Links:

lib/auth/auth-config.ts (Changes)
// Remove or comment out:
// import Resend from "next-auth/providers/resend";
 
// Add:
import SendGrid from "next-auth/providers/sendgrid";
 
// ... inside providers array
 
// Remove or comment out:
/*
Resend({
  from: appConfig.resend.fromNoReply, // Ensure this was the previous config if commenting out
}),
*/
 
// Add:
SendGrid({
  from: appConfig.sendgrid.fromNoReply, // Use SendGrid config
}),

6. SendGrid Account Setup

Follow these steps to set up your SendGrid account for sending:

  1. Create Account: Sign up at SendGrid.
  2. Sender Authentication: Set up Domain Authentication (recommended) or Single Sender Verification. Follow SendGrid's guides to add the necessary DNS records (CNAMEs) for your domain or subdomain (e.g., mail.yourdomain.com).
  3. Create API Key: Go to Settings > API Keys > Create API Key. Name it (e.g., YourAppName Production) and assign Mail Send permissions (Full Access also works). Copy the key immediately.
  4. Store API Key: Add the key to your .env.local as AUTH_SENDGRID_KEY (as done in step 4).

Sending & Receiving

  • Sending: The sendEmail function in lib/sendgrid.ts now handles sending via the SendGrid API.
  • Receiving: To handle replies, ensure the reply_to option is set correctly when sending emails. Our centralized sendEmail function usually handles this by setting reply_to to the supportEmail defined in your app-config.ts.

Checklist to Avoid Spam Folder (SendGrid)

  • Verified Sender: Ensure your sending domain/subdomain or single sender is fully authenticated in SendGrid.
  • Proper DNS: Correct CNAME/MX records for SendGrid domain authentication are essential. Implement SPF, DKIM, and DMARC.
  • IP Reputation: Monitor your sender reputation using SendGrid's tools. Consider a dedicated IP for high-volume sending.
  • Reputation: Maintain a good sender reputation by:
    • Sending relevant, expected content.
    • Managing bounces, blocks, and spam reports promptly through SendGrid's suppression lists or via webhooks.
    • Warming up new domains/IPs gradually.
  • Content: Avoid spammy content, excessive links, misleading subject lines, and large attachments.
  • List Hygiene: Regularly clean your email lists to remove inactive or invalid addresses.
  • Unsubscribe Link: Always include a clear and functional unsubscribe link, ideally using SendGrid's subscription tracking.

On this page