Send emails with SendGrid

import sgMail from '@sendgrid/mail'

// Set SendGrid Api key

export default async function handler(req, res) {
  const { name, email, message } = req.body

  const msg = `
    Name: ${name}\r\n
    Email: ${email}\r\n
    Message: ${message}

  const data = {
    to: '',
    from: '',
    subject: 'New email from...',
    text: msg,
    html: msg.replace(/\r\n/g, '<br>'),

  try {
    await sgMail.send(data)

      message: 'success',
  } catch (error: any) {
      message: 'fail',

How to use


Login in your SendGrid Account

Login to your SendGrid account, if you don’t have one, you can create one here


Add Sender Auth

We need to let SendGrid know which domains are authorized to send emails. To do this:

  1. In your SendGrid dashboard, navigate to settings (on the left panel).
  2. Click on Sender Authentication -> Authenticate Your Domain. Add your domain info.
  3. Once you’re finished, you should get 3 new DNS Records to add to your DNS provider.

Generate your API Key

In your dashboard, go to settings -> API Keys. Click on Create API Key.

Give your key a meaningfull name so you can remember what it does. Then select API Key Permissions and create your key.

Remember to save your key in your .env.local file inside your Next Js project and don’t push it to Github.


Create API route

Inside your api folder add the code snippet in your project API route. You can name the route however you want.