How to integrate Serverless contact form using Firebase Cloud functions in React

To create serverless contact forms, you need a service like Google Cloud Functions and its powerful cloud functions. In this tutorial I will show you how to create a contact form with Firebase and React. Our contact form will send us notification emails and will write an entry in Firebase Database, so we won't delete or lose messages.

First, you will need a Google Account and sign in into the Firebase console admin panel. Next step is to create/add a project from which you will have access to a Hosting, Realtime database, Cloud functions, etc. We can find here the list of all the Firebase products. Finally, we need to initialize Firebase in our project. You have two options:

If we need to choose Firebase services, like functions, hosting and database, execute in the console the command (this should be our case):

firebase init

After that follow the instruction and check the services we want to use like functions, database, hosting, etc.

Our contact form will send us notification emails and will write an entry in our Firebase Database.

Start writing code

Back-end

We will start with the back-end part. Firebase uses NodeJS server and to write code, you need to navigate to functions folder and open index.js. We can find the folder after functions initialization mentioned above.

The packages we need to continue are firebase-functions, nodemailer, cors. First one is to initiate functions, the second one is to help send emails and the last one is to enable Cross-origin (CORS) requests. We will use the last one only if we will use custom domain.

As an email service we will use Gmail. It's the easiest to set and we already have an account for firebase.
To protect our email and password, we will take advantage of Environment configuration, we don't want to expose our credentials. Open the terminal in the root folder of the project and type:

What we did is to send to ourselves email with data from a POST request. From here we can extend our function to test if data typed by the user is correct or attempt to breach security or whatever we want.

Pro Tip

At the time of writing this blog post Firebase npm package is version 5.8.3. The package is referring to the global object window which is a problem. The problem is that if we are using an environment that has no window object for example site generator like Gatsby or whatever with NodeJS we will get an error :

window.self is not defined.

If you bumped to this error, there is a simple workaround. Don't import firebase from 'firebase/app';. And initialize the app like that: