loading...
Cover image for Integrating SendGrid with Next.js :)

Integrating SendGrid with Next.js :)

markdrew53 profile image Mark Drew ・4 min read

Hi friends, this first post in dev.to : ) In this tutorial I will teach you in 5 simple steps create a service to send email using API routes with Next.js.

What is SendGrid

It is a very popular service that through the communication of its API allows you to send an email to any customer you have in your application. I would like to highlight that it is used by large companies such as UBER, Spotify, airbnb, yelp. You can get more detailed information about the service here

What is Next.js

It is an all-in-one solution that allows you to create static as well as dynamic websites. An excellent option for those interested in JAMStack.

Create Next App

npx create-next-app next-sendgrid

Add scripts object

In this step we will dedicate ourselves in the structure that our project requires.

After having installed the dependencies, your project should look this way.

Alt Text

Now add the scripts object, which will have all your commands npm or yarn

Alt Text

Finally we have to create the folder /pages, inside the folder create the file index.js, registry.js and the folder /api. Inside the / api folder we will create the route send-email.js

Alt Text

Step 3

In programming it is a good practice to reuse the functions that we usually use a lot, for this reason we will create a /utils folder in the root of our project, which will contain the following file

Alt Text

sendEmail.js

import fetch from 'node-fetch'

const SENDGRID_API = 'https://api.sendgrid.com/v3/mail/send'

const sendEmail = async ({ name, email }) => {
    await fetch(SENDGRID_API, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${SENDGRID_API_KEY}`
        },
        body: JSON.stringify({
          personalizations: [
            {
              to: [
                {
                  email
                }
              ],
              subject: 'Demo success :)'
            }
          ],
          from: {
            email: 'noreply@demo.com',
            name: 'Test SendGrid'
          },
          content: [
            {
              type: 'text/html',
              value: `Congratulations <b>${name}</b>, you just sent an email with sendGrid`
            }
          ]
        })
    });
}

export { sendEmail };

If you want to know why the scheme to send an email is designed in this way, you can know more information here

/api/send-email.ts

API routes provide a straightforward solution to build your API with Next.js. You might be wondering what the advantage is instead of express another similar solution.

API Routes: serverless
express: server

the advantage that focuses on serverless is that you build your api based on functions, reducing error rate. It is invoked when necessary. With the traditional server approach, your API can be online even if nobody is consuming it, increasing the payment costs of your hosting provider.

import { NextApiRequest, NextApiResponse  } from 'next';

import { sendEmail } from '../../utils/sendEmail';

export default async (req: NextApiRequest, res: NextApiResponse) => {
    if(req.method === 'POST') {
      const { name, email } = req.body;
      await sendEmail({ name, email });
      return res.status(200).end();
    }
    return res.status(404).json({
        error: {
            code: 'not_found',
            messgae: "The requested endpoint was not found or doesn't support this method."
        }
    });
}

Step 4

In this step we will focus on creating the key to be able to use sendGrid in our api, first of all you will have to create an account on the next page. Once you access your dashboard, go to the next option

Alt Text

When you select the option you should see the following

Alt Text

once you have finished generating your api key, we will make a small modification in our file sendEmail.js

import fetch from 'node-fetch'

const SENDGRID_API = 'https://api.sendgrid.com/v3/mail/send'
const SENDGRID_API_KEY = 'YOU_KEY'

const sendEmail = async ({ name, email }) => {...}

export { sendEmail };

Step 5

In this last step, what we will do is implement the UI so that they can send the email. The design is excessively simple.

/pages/index.js


import React from 'react';

import Registry from './registry';

const Index = () => <Registry />;

export default Index;

/pages/registry.js

import React, { useState } from 'react';

const Registry = () => {
    const [state, setState] = useState({ name: '', email: '' });
    const handleChange = event => {
      const { name, value } = event.target;
      setState({
        ...state,
        [name]: value
      });
    }
    const handlePress = () => {
      fetch('/api/send-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: state.name, email: state.email })
      });
    }
    return (
        <>
      <div>
      <label>
        Name
        <input
          name="name"
          type="text"
          onChange={handleChange}
        />
      </label>
      </div>
      <label>
        Email
        <input
          name="email"
          type="email"
          onChange={handleChange}
        />
      </label>
      <div>
      <button onClick={handlePress}>Send</button>
      </div>
        </>
    );
}

export default Registry;

In case you wonder how to handle many input with React I recommend the following article where they explain in detail the pattern I am using for this tutorial. Returning to the main topic, once you have completed all the steps you should see the following results.

Alt Text

Alt Text

project resources: https://github.com/MAPESO/nextjs-sendgrid

Posted on Jan 8 by:

Discussion

markdown guide
 

Hey Mark, thanks for the tutorial.
Do you know why Im having an error 404 when send an email?
I received the emails but the page turn 404 and the url of browser result "localhost:3000/page?name=Julian&email=test@mail.com&message=a_message" instead "localhost:3000/api/send-email"
I tested with postman and sendgrid return an 202 Accepted.
can you help me? thanks a lot