Send Transactional Emails With Next.js and SendinBlue

Introduction

Next.js is a wonderful Framework based on React that allows us to render views from the server side. In this tutorial, we will use Next.js with Sendinblue to send transactional emails. Sendinblue is a comprehensive suite of SaaS communication tools, including email marketing, transactional emails, text messages, and more. To complete this tutorial, you’ll need a free Sendinblue account.

Prerequisites?

For this tutorial you don’t have to be an expert in Javascript. Basic knowledge is enough to get the hang of this tutorial.

Setting up Next.js App

You should have npm installed in your computer. First create a folder called ‘Sendinblue’ for this tutorial and navigate to your project folder in the console. Mine is:

cd ~/Sendinblue

Create a file called ‘package.json’ in your project root folder. You can create a file in terminal:

touch package.json

Add this content to the package.json file:

{
  "name": "SendinBlue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "start": "next start",
    "build": "next build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "^9.2.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  }
}

Moving on open your terminal and run ‘npm i’ - this will install all the necessary dependencies for the Next.js app.

When you are done with installing dependencies please create a folder called ‘src’ and then within this another folder called ‘pages’ inside ‘src’ folder. Then create a new file called ‘index.js’ inside the pages folder. Your path should look like this ./SendinBlue/src/pages/index.js

Now add these content to the index.js file:

function HomePage() {
  return(<div>Hello there</div>)
}

export default HomePage;

Back to your terminal and run ‘npm run dev’ when you see this

ready - started server on http://localhost:3000

on your terminal please go to your browser and open up http://localhost:3000

You should see a white screen with hello there text. Congratulations you just set up a Next.js app 🎉🎉🎉

Server Side Rendering With Express

We need some server side language to send emails with SendinBlue API. Next.js support Server Side Rendering with express.js

In order to do this, you need to create file called ‘server.js’ in your root folder and add this content:

const express = require("express");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();
    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });


  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

when you have done this please update script tag on package.json file like this:

  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "staging": "NODE_ENV=staging next",
    "start": "NODE_ENV=production node server.js"
  }

Your package.json file should look like this:

{
  "name": "sendinblue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "staging": "NODE_ENV=staging next",
    "start": "NODE_ENV=production node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "^9.2.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  }
}

now go to your terminal and first add express to our dependencies. Please run:

    npm install --save express

Now try to run the app again:

    npm run dev

You will see our app is running again with express js.

Building the frontend

For this tutorial we will create a simple button that send a transactional email using SendinBlue once the user click the button. Let’s create a simple input and button. Please open up index.js file and replace the content with the following:

  function HomePage() {
   const buttonWrapperStyle = {
    color: "white",
    display: "inline-block",
    backgroundColor: "DodgerBlue",
    padding: "10px",
    fontFamily: "Arial",
    maxWidth: '240px',
    margin: '0 auto',
    borderRadius: '3px'
  };

  return(<div style={buttonWrapperStyle}>
      <input type="text" value="https://craftcode.design/" /><button>Send me this url</button>
    </div>)
}

export default HomePage;

You will have a simple Frontend like this: Register

Setting up an endpoint to send the email:

In order to send an email we need to have an endpoint available to our frontend because we cannot send an email directly from the client side (at least we should not). In this case we are going to use express.js to create a new route for us. Please add this to your server.js

server.use(bodyParser.json()).post('/api/email', (req, res) => {
      const { email = '', msg = '' } = req.body; //We will use this later
    
      res.send('success');

});

As you can see we also use a new package ‘bodyParser’. We will need to require this on the top of the file.

const bodyParser = require('body-parser');

then also run this on your terminal

 npm install body-parser

now the server.js file should look like this:

const express = require("express");
const next = require("next");
const bodyParser = require('body-parser');
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();
    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });

    server.use(bodyParser.json()).post('/api/email', (req, res) => {
      const { email = '', msg = '' } = req.body; //We will use this later
    
      res.send('success');

    });


  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

So moving on, it’s time to create an account on SendinBlue. Please navigate to sendinblue.com and create a free account.

Once you landed on the account creation page you will see this view: Register

then you will be directed to the dashboard: Dashboard

when you are ready click on the transational tab on the main navigation. Transactional

click on the templates and start creating a new template: Transactional

You can use any name for your template. Next, let’s move onto the design tab. For this tutorial I have created a very simple design. Make sure to keep {{params.link}} in the design. We will use this to send dynamic data from our next.js app. Transactional Email Design

Please activate the template and then you are all set in the SendinBlue platform for now. Let’s move on to Next.js part where we are going to use an ajax call to our /api/email endpoint.

Calling email api endpoint

Remember back to where we created an endpoint in server.js for ‘/api/email’. Now it’s time to send a test request from the Frontend. For this tutorial I am going to use Axios package for sending ajax request from the frontend. There are plenty of ways to implement this but for the sake of this tutorial I will make it very simple. Please create a folder called ‘services’ inside /src/ folder. Then create another file ‘sendMail.js’. We are going to write a simple service to call ‘/api/email’ endpoint. Inside ‘sendMail.js’ add this content:

import axios from "axios";

export const sendMail = async (link) => {
  try {
    let request = await axios
      .post("/api/email", {
        name: "Malith",
        email: "[email protected]",
        subject: "Someone sent you a Link.",
        msg: link,
      })
      .then((res) => {
        return res;
      });
    return request.status === 200 ? true : false;;
  } catch (err) {
    console.error(err);
  }
};

and then you need to import this service into your nextjs page. Open up ‘/src/pages/index.js’ file and import the sendMail like this:

import { sendMail } from "../services/sendMail";

Now we need to call this function whenever someone clicks on the ‘Send me this url’ button. Moving on we need to create an async function called handleOnClick (you can call this whatever you want).

async function handleOnClick (){
    let response = await sendMail('https://craftcode.design/');
    console.log(response);
}

Now you can attach this to the button easily like this: onClick={ () => handleOnClick()}.

Complete index.js content should look like this:

import React, { useState, useEffect } from "react";
import { sendMail } from "../services/sendMail";


function HomePage() {

  async function handleOnClick (){
    let response = await sendMail('https://craftcode.design/');
    console.log(response);
  }

  const buttonWrapperStyle = {
    color: "white",
    display: "inline-block",
    backgroundColor: "DodgerBlue",
    padding: "10px",
    fontFamily: "Arial"
  };

  return(<div style={buttonWrapperStyle}>
      <input type="text" value="https://craftcode.design/" /><button  onClick={ () => handleOnClick()}>Send me this url</button>
    </div>)
}

export default HomePage;

If you go to your browser and open your console then click on the button. You will see a response ‘true’. This validate email endpoint is working and our axios request works as well.

Last step

We are almost done. Let’s move on to the part where we actually send the email. In order to do this we will need a package from sendinblue called ‘sib-api-v3-sdk’. Switch to the terminal and run ‘npm install sib-api-v3-sdk’. Then create a folder called ‘api’ in the root and inside this folder you need to create a file with the name ‘sendinblue.js’

Add this content to the sendinblue.js:

const SibApiV3Sdk = require('sib-api-v3-sdk');
const defaultClient = SibApiV3Sdk.ApiClient.instance;

// Configure API key authorization: api-key
var apiKey = defaultClient.authentications['api-key'];
apiKey.apiKey = 'ADD-YOUR-API-KEY-HERE';

var apiInstance = new SibApiV3Sdk.SMTPApi();

const sendinblue = (sendSmtpEmail) => {
  apiInstance.sendTransacEmail(sendSmtpEmail).then(function(data) {
      return true;
    }, function(error) {
      console.error(error);
      return false;
    });
}

module.exports = sendinblue

You need to replace the apiKey with your api key. You can get it from your SendiBlue dashboard top right corner:

API KEY

Once you are done with replacing the API key please go back to the server.js and import the sendinblue function and call the transactional mail api like this:

const sendinblue = require('./api/sendinblue');
  server.use(bodyParser.json()).post('/api/email', (req, res) => {
      const { msg = '' } = req.body;
      let sendSmtpEmail = {
        to: [{
            email: '[email protected]' 
        }],
        templateId: 1,
        params: {
          name: 'Malith',
          subject: 'Someone sent you a link',
          text: msg,
      },
      };
      sendinblue(sendSmtpEmail)
      res.send('success');
    });

the complete server.js file should look like this:

const express = require("express");
const next = require("next");
const dotenv = require("dotenv");
const bodyParser = require('body-parser');
const sendinblue = require('./api/sendinblue');


dotenv.config();

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();
    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });

    
    server.use(bodyParser.json()).post('/api/email', (req, res) => {
      const { msg = '' } = req.body; //We will use this later
      let sendSmtpEmail = {
        to: [{
            email: '[email protected]' //TODO: Change this on production.
        }],
        templateId: 1,
        params: {
          name: 'Malith',
          subject: 'Someone sent you a link',
          text: msg,
      },
      };
      sendinblue(sendSmtpEmail)
      res.send('success');
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

This was the last part. Now we can start testing. Go back to the frontend and click on the ‘Send me this url’ button. It should send you an email with the template and content we created. This is what my email looks like:

EMAIL

In case you missed something, you can fork this github repo I made for this tutorial.

Conclusion

Thanks for reading! I hope this article provides some insight into how easy to use SendinBlue api and send transactional emails.

If you have any questions or remarks, leave a comment below.

Get The Best Of All Hands Delivered To Your Inbox

Subscribe to our newsletter and stay updated.