Simple contact form with Vue and Firebase
In this blog post, I will guide you through the creation of a simplistic contact form using two of the most popular technologies recently – Vue.js and Firebase.
Prerequisites
Here is all you need installed before we begin:
- Node.js (> 8.9 )
- Vue CLI (optional but highly recommended)
- Firebase CLI
npm install -g @vue/cli firebase-tools
After the dependencies have been installed, create a fresh Vue project:
vue create contact-form
Firebase setup
Before we start coding, let’s create a new Firebase project first. Open the Firebase Console and create a new project. I will name mine “Vue Contact Form” but the naming doesn’t matter at all.
Now open the command line from the folder of your Vue project and run the following command:
firebase init
You will be asked a couple of questions. Make sure you select “Functions” to the question “Which Firebase CLI features do you want to set up for this folder?”. After that, a new folder “functions” will be created with some boilerplate code in it. Open the command line from the functions folder and install the necessary dependencies with the following commands:
npm install --save nodemailer cors
In order to send emails from our Firebase functions, we need nodemailer and cors to allow Cross-Origin Resource Sharing (CORS).
After that add the following code to the index.js file in your functions folder.
For the purpose of this tutorial, I’m using the mail server offered by Gmail, which is one of the easiest options to set up. Of course, you can use whatever mail server you like. You can find how to configure nodemailer in its documentation.
As you can notice, all the code is wrapped inside the cors middleware. That’s due to the browser’s restrictions and the errors that may occur when you send an HTTP request to the Firebase server.
We use the functions.https.onRequest hook, which gets triggered on each HTTP request to the URL of our function. The function handler looks exactly like Express middleware, so nothing groundbreaking here. Inside the handler, we use nodemailer’s API to send a mail with the transport that we created. The sendMail function returns a Promise and based on its result, we return an HTTP response using the response provided by Firebase.
To run the functions locally, run the following command:
firebase emulators:start --only functions
The ContactForm component
Now that we have Firebase and the Firebase functions setup, it’s time to create the Front End of our application. In this tutorial, I won’t focus on the styling but rather on the logic. You can find the component’s code below:
Below is the ContactForm component I created:
As you can see, the implementation is pretty straightforward. We sent POST request to the firebase function URL and based on the result we display a success or error message.
Conclusion
In this short tutorial, we created a simple contact form using Vue.js and Firebase functions. The full code in the Github repo.