Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

step by step guide to creating a fully functional contact form using firebase

Name

Email

Message



Having a fully functional contact form on your website gives your web viewers a channel to communicate with you anytime. In this tutorial, I will be creating a fully functional contact form with email notification using  Firebase Functions. The above contact form is the end product of this tutorial and its fully functional, if you fill the form, it will send a message to the email in the email section.

PREREQUISITE

In this tutorial HTML, CSS, JavaScript and Firebase Functions will be used to create the contact form.

STEP 1 : HTML

In the HTML section we have two input elements and a textarea element that will be used to collect a visitor's name, email and message respectively.

<div class="container-out">
  <div class="container-in">
    <div class="contact-form">
      <p>Name</p>
      <input type="text" id="contact-name" />
      <p>Email</p>
      <input type="email" id="contact-email" />
      <p>Message</p>
      <textarea id="contact-message"></textarea>
      <button id="send">Send</button>
    </div>
  </div>
</div>

STEP 2: STYLE THE CONTACT FORM

Adding styles to the contact form

.container-out {
  font-family"Fira Sans"sans-serif/* adds font obtained from google fonts */
  padding15px 0/* adds padding at the top and bottom of the outer container */
  max-width400px/* gives the outer container a maximum width of 400px */
  margin0 auto/*centers the outer container in the middle of the body */
}

.container-in {
  padding30px 0/* adds padding at the top and bottom of the inner container */
  width95%/* width of inner container equals 95% of the outer container */
  margin0 auto/*centers the outer container in the middle of the outer container */
  background#168ab8/* gives the inner container a background color */
  border-radius5px/* curves the edges of the inner container by 5px */
}

.contact-form {
  width85%/* width of inner container equals 85% of the inner container */
  margin0 auto/*centers the outer container in the middle of the inner container */
}

.contact-form p {
  margin0/* removes all margins from the p tags */
  margin5px 0/* add 5px margin at the top and bottom of the p tags */
  colorwhite/* changes the text color of the p tag to white */
}

.contact-form input {
  bordernone/* removes the border on the input */
  width100%/* makes the input width same as the contact-form div*/
  margin-bottom15px/* adds margin at the bottom of the input */
  padding10px/* adds 10px padding to all sides of the input */
  box-sizingborder-box/* prevents the input from overflowing out of the parent div */
  border-radius3px/* curves the edges of the input by 3px */
}

.contact-form textarea {
  width100%/* makes the textarea width same as the contact-form div */
  padding10px/*  adds 10px padding to all sides of the input */
  box-sizingborder-box/* prevents the input from overflowing out of the parent div */
  border-radius3px/* curves the edges of the input by 3px */
  min-height120px/* gives the text-area a minimum height of 120px */
  margin-bottom15px/* adds margin at the bottom of the textarea */
  resizevertical/* limits resizing to vertical resizing */
}

.contact-form button {
  bordernone/* removes the border on the button */
  padding7px/*  adds px padding to all sides of the button */
  background#e8f8ff/* gives the button a background color */
  color#168ab8/* changes the text color of the button to white */
  border-radius4px/* curves the edges of the button by 4px */
  cursorpointer/* changes the mouse pointer when you hover over the button */
  font-weightbold/* boldens the text of the button */
}

.contact-form button:hover {
  opacity0.7/* changes the opacity of the button to 0.7 on hover */
}

STEP 3: JAVASCRIPT WITHOUT FIREBASE

The JavaScript section is pretty straight forward, all it does is validate your information and sends it to Firebase for emailing. 

document.getElementById("send").addEventListener("click", validateForm);
function validateForm() {
  //gets the name
  let name = document.getElementById("contact-name").value;
  //gets the email
  let email = document.getElementById("contact-email").value;
  //gets the message
  let message = document.getElementById("contact-message").value;

  //checks if all fields have been filled before sending message.
  if (name.trim() == "" || email.trim() == "" || message.trim() == "") {
    alert("all fields must be filled");
  } else {
    sendMessage(name, email, message);
  }
}

STEP 4: FIREBASE FUNCTIONS

Firebase Functions are apps your write and store on Google servers to solve a particular problem. Firebase Functions are deployed with codes written in Node.js. If you are new to Firebase Fucntions Watch the youtube video below to get started 

INSTALL NODE.JS

After you must have created your project on Firebase , the next thing you have to do is install Node.js, so head over to https://nodejs.org/en/download/ , download and install Node.js.

CREATE FUNCTION FOLDER

After installing Node.js, create a folder anywhere on your PC, open your desired terminal application and set the terminal's  directory to your created folder's directory as shown below

I have created a folder myFunction in my Google Drive folder, next i will  open command prompt and change directory to myFunction's directory as show below

At this point we are ready to install Firebase tools on your system.

Run the command below in the command prompt to install the tools.

npm install -g firebase-tools

After installing Firebase tools, you can now login using the Gmail you created your project with, using the following command

firebase login

you will then be redirected to Sign In with Google. After Sign in is done, you'll have to install the functions files that comes with the index.js file that will contain all your apps. Enter the following command to install these files

firebase init function

You will be asked a couple of questions, answer them and finish the installation.

a new folder named functions will be created in your myFunction directory, change your command prompt's directory to the functions directory and run the command below to install nodemailer

npm install nodemailer cors

This will install nodemailer in your Firebase Functions.

Now we are ready to create our function and deploy it. Open the functions folder in your myFunction folder and open index.js with your desired text editor. This is where your Node.js code will go. Below is a function that sends an email whenever a message is sent from the contact form.

const functions = require("firebase-functions");
const nodemailer = require("nodemailer");
const cors = require("cors")({ origin: true });
/**  * using gmail with nodemailer  */

let transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    user: "naishareapp@gmail.com",
    pass: "*******",
  },
});

exports.sendMail = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    // getting dest email by query string
    const email = req.query.email;
    const name = req.query.name;
    const message = req.query.message;
    const mailOptions = {
      from: "Naishare <naishareapp@gmail.com>",
      to: "youremail@gmail.com",
      subject: "Contact Form Message"// email subject
      html:
        `           
<div>             
From:` +
        name +
        `<br /><br />              
Email: ` +
        email +
        `<br /><br />             
Message:` +
        message +
        `<br /><br />           
</div>           
`// email content in HTML
    };
    // returning result
    return transporter.sendMail(mailOptions, (erro, info) => {
      if (erro) {
        return res.send(erro.toString());
      }
      return res.send("Message Sent");
    });
  });
});

After saving your index.js file, head over to your terminal and change directory to the myFunction folder and run

firebase deploy

This command uploads your index.js file to the Google cloud servers and a url will be generated to be used whenever you want to send an email. By adding url parameters to the url we can send parameters across to the cloud function. This url can be obtained from your Firebase console in the Functions section.

STEP 6: JAVASCRIPT WITH FIREBASE

Now that we have deployed and obtained our url, we can now pass the name, email and message of our website visitors as url parameters for emailing.

document.getElementById("send").addEventListener("click", validateForm);
      function validateForm() {
        //gets the name
        let name = document.getElementById("contact-name").value;
        //gets the email
        let email = document.getElementById("contact-email").value;
        //gets the message
        let message = document.getElementById("contact-message").value;

        //checks if all fields have been filled before sending message.
        if (name.trim() == "" || email.trim() == "" || message.trim() == "") {
          alert("all fields must be filled");
        } else {
          sendMessage(name, email, message);
        }
      }

      //sends information to firebase
      function sendMessage(name, email, message) {
        //sends the name, email and message by passing them as url parameters
        window.location.href =
          "https://us-central1-naishare.cloudfunctions.net/sendMail?name=" +
          name +
          "&email=" +
          email +
          "&message=" +
          message +
          "";
      }

The sendMessge() function attaches the name, email and message as url parameters and sends it to our sendMail function stored on Google Cloud Servers.

CONCLUSION

In this tutorial we saw how to build a fully functional contact form without hosting your site. With Firebase all your apps are run on Google servers so you don't have to worry about configuring servers.