posts about software engineering craft

Live Coding #1 mail subscription service in nodejs with fastifyjs and markojs as frontend framework.


In this article, I will show how to create a mailer service using mailjet and add it to an existing fastify project. This is part 1 of a multipart series where I will live-code a subscription feature for the existing blog.

Mailjet configuration

Step 1

Create API_KEY and the SECRET_KEY in Mailjet->API Key Management.

Export them in environment variables.

export MAILJET_API_KEY="c***************************3ecd"
export MAILJET_SECRET_KEY="8******************************6"

Step 2

Install the node-mailjet library. In this tutorial I am using the version ^6.0

npm istall node-mailjet --save

Create a fastify plugin

// mailjet.js
'use strict';

const fp = require('fastify-plugin');
const Mailjet = require('node-mailjet');

module.exports = fp(async function (fastify) {
  const mailerClient = new Mailjet({
    apiKey: process.env.MAILJET_API_KEY,
    apiSecret: process.env.MAILJET_SECRET_KEY,
  }).post('send', { version: 'v3.1' });

  fastify.decorate('mailerClient', mailerClient);

Usage in a fastify route

module.exports = async function (fastify) {
  const { mailerClient } = fastify;
  const { badRequest } = fastify.httpErrors;"/send-mail", async (request) => {
    try {
      const message = {
        Messages: [
            From: {
              Email: "",
              Name: "John Doe",
            To: [
                Email: "",
                Name: "Katy Shield"
            Subject: "Some subject",
            TextPart: "Some text",
            HTMLPart: "<h3>Some email</h3>",
            CustomID: "AppGettingStartedTest",

      await mailerClient.request(message);
    } catch (err) {
      throw badRequest();

This will be the minimum code needed to create a fastify plugin using the node-mailjet.

I went a different route during the live coding session to have a cleaner code. If you are interested in my approach, follow the youtube session.

I hope that this article was helpful. If you like it, please share it with your friends and leave a comment; I will gladly answer all the questions.