Send a 'Welcome' Email after someone signs in to your Firebase🔥 App with Brevo
Tags: webdev, firebase, javascript, beginners
Published: 2023-07-14 13:54:30

## Introduction
Today, I will show you how to automate the process of sending a welcome email to a new user upon sign-up with Firebase Authentication, using Firebase Functions and Brevo's email service. It's very easy...  

Firebase is definitely the best backend provider in my opinion and you can create a full Web App with the **FERN stack - Firebase Express React Node**

Brevo is a very easy to use **'Email Builder'**, because the content in the email is rich...and you can also make customer lists here. However a simple way to make a welcome mail is to just make one and Store it as a template. And then send to everyone.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pfj9e00jgysxyvajyily.png)

My Project is [Helicity.ai](https://helicity.ai) , an AI powered JS Game Engine still in the works.


## Setting Up Firebase Authentication
First, you need to set up Firebase Authentication on your platform. Firebase provides a simple, secure, and free system for this purpose. 

You can use a library like [firebaseui-web-react](https://github.com/firebase/firebaseui-web-react) to make your **Sign in with Google** Button.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eypj83aec8o3b1scqgm2.png)
Firebase will handle everything else for you and when you go to your project page you can see everyone and their UUID which uniquely identifies them. Even if they use Email sign in or Phone or all the other ones firebase offers.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x88embcpnpph8azh94cu.png)




## Creating a Firebase Function
We will create a Firebase Function that triggers whenever a new user signs up. Firebase Functions are essentially small pieces of backend code that can be executed in response to various events.

Here is the code for our function:

```javascript
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.onUserSignUp = functions.auth.user().onCreate(async (user) => {
  // User signed up
  const uid = user.uid;
  const email = user.email;
  const displayName = user.displayName;

  // Write to RTDB
  await admin.database().ref(`users/${uid}`).set({
    email: email,
    displayName: displayName,
    credits : 34,  //How many prompts this guy can use today
    // Add any other fields you want to save
  });

  var c = await sendBrevoEmail(email, 6);
  console.log(c);
});
```

In the function `onUserSignUp`, Firebase passes a UserRecord object representing the newly created user to our function. The function then writes the user's information to Firebase's Realtime Database (RTDB) and attempts to send a welcome email through Brevo. The RTDB record looks like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/px6az9tibvws9bur6udu.png)



## Sending an email through Brevo with an API request
To send the email, we are going to use Brevo's API. We will create a function called `sendBrevoEmail` that takes an email address and a template ID as parameters:

Most of this is boilerplate so don't bother much. What's important is who you send the email to and the template ID. You can go to your brevo project and see all the templates and IDs.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/op818vu5ahic4h0m6pir.png)



```javascript
const SibApiV3Sdk = require("sib-api-v3-sdk");
async function sendBrevoEmail(email, templateId) {
  let defaultClient = SibApiV3Sdk.ApiClient.instance;

  let apiKey = defaultClient.authentications["api-key"];
  apiKey.apiKey =
    "xkeyDONTSTEALMINEPLEASE7QvM";

  let apiInstance = new SibApiV3Sdk.TransactionalEmailsApi();

  let sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail();

  sendSmtpEmail.templateId = templateId; // 6 is google , 5 is early access
  sendSmtpEmail.sender = { name: "Helicity.ai", email: "lilshake@helicity.ai" };
  sendSmtpEmail.to = [{ email: email }];

  apiInstance.sendTransacEmail(sendSmtpEmail).then(
    function (data) {
      console.log("API called successfully.");
    },
    function (error) {
      console.error(error);
    }
  );
}
```

##Extras - Using Formspark✨ to also send an email when someone signs up for Early Access
Formspark is another UI widget manager that looks like this once you set it up. It has a list of the people who signed up and can POST this information to our ENDPOINT.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jzp0viy5mv55e9hnv9l.png)

#A new firebase Function
Okay so the previous one was for google sign ins. This is for people who have provided their Email for a Newsletter/Early Access. 

```javascript
exports.sendBrevoEmail = functions.https.onRequest(async (req, res) => {
  if (req.method !== "POST") {
    res.status(400).send("Bad request, expecting POST");
    return;
  }

  const email = req.body.email; // Extract the email from the Formspark request

  try {
    await sendBrevoEmail(email, 5);
    res.status(200).send("Email sent");
  } catch (error) {
    console.error(error);
    res.status(500).send("Failed to send email");
  }
});
```
Firebase will give you an endpoint which you will need to set as the webhook URL in Formspark

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57qyv224ribwllimsczn.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9b3h9111yu2no21jp8ir.png)




## Conclusion
As you can see, sending an email upon user sign-up is a breeze with Firebase Functions and Brevo's API. With this method, you can ensure that every new user gets a warm welcome without any manual intervention. Happy coding!

**You can try this out right now! Make an account on helicity.ai and you will receive an email.**
If you like this and are interested in the development, do consider joining the [discord](https://discord.com/invite/RkH98RgVDr) server!

Here is the [Github](https://github.com/lil-shake-code/helicity.ai)

The Helicity.ai Team 🚀