Integrating SendGrid with Next.js :)
Tags: react, node, nextjs, zeit
Published: 2020-01-08 19:44:36

---
title: Integrating SendGrid with Next.js :)
published: true
description: 
tags: react, node, nextjs, zeit
cover_image: https://thepracticaldev.s3.amazonaws.com/i/eqqeg37dzaqw0t1loi1d.png
---

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](https://sendgrid.com/)

# 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](https://thepracticaldev.s3.amazonaws.com/i/jhho9bv3bq7qy2xfyqb7.png)

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

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/skcmyvyh94tt66kuwk78.png)

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](https://thepracticaldev.s3.amazonaws.com/i/8csi5mgs1girzf3tqezg.png)

### 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](https://thepracticaldev.s3.amazonaws.com/i/kc3xwoau1la33m7xx3ml.png)

**sendEmail.js**




```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] (https://sendgrid.com/docs/api-reference/)

**/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.
```js
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.] (https://signup.sendgrid.com/) Once you access your dashboard, go to the next option

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/bhzntna0y610hi1d7a46.png)

When you select the option you should see the following

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/oevqfwsn5t1zwnbh2v2o.png)

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

```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`


```js

import React from 'react';

import Registry from './registry';

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

export default Index;

```

`/pages/registry.js`


```jsx
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] (https://www.pluralsight.com/guides/handling-multiple-inputs-with-single-onchange-handler-react) 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](https://thepracticaldev.s3.amazonaws.com/i/19y08h07tqwe08xuw5tm.png)


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/z0f9wvnh1674b95ur4xa.png)

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