29 Aug 2023 · Software Engineering

    Creating a Newsletter Page With Vue and Firebase Cloud Firestore

    9 min read
    Contents

    Having a newsletter signup feature on our website is an essential part of our digital strategy. It enables us to expand our email list and keep our subscribers updated with our latest products, stories, blogs, new features, and other business developments. This feature also helps us market our products to a sizable and diverse consumer base. In this article, we will explore what Firebase and Cloud Firestore are, and how to create a powerful newsletter signup page using Vue, Firebase, and Cloud Firestore.

    Prerequisites

    Before proceeding with this article, ensure you meet the following requirements:

    Check out the full code on Github

    • Vue project created and set up
    • Node.js installed with the latest version
    • Basic understanding of working with Tailwind CSS and Vue, as we won’t discuss that in this article

    Definition of Firebase and Cloud Firestore

    Firebase is a backend cloud computing service and application development platform created by Google. It provides developers with a suite of tools for building and managing applications. Firebase includes various features, such as authentication, cloud storage, and a real-time database for a range of applications—including Android, JavaScript, Node.js, PHP, C++, and Java.

    Cloud Firestore is an advanced, cloud-hosted NoSQL database offered by Firebase and Google Cloud. Designed for scalability and high-performance querying, it serves mobile, web, and server development. The database keeps data synchronized across client apps through real-time listeners. Additionally, it offers offline support for mobile and web applications, enabling the design of performant applications independent of internet connectivity. Cloud Firestore is accessible via native SDKs for Apple, web, and Android apps.

    Create Our Firebase Project

    After meeting the prerequisites, the next step is to create a new Firebase project. To do so, visit or log in to the Firebase console website. Click on the Add Project button.

    In the next step, we’ll name our project; for this example, we’re calling it newsletter-page.

    Optionally, you can incorporate Google Analytics into the website. Although this is not mandatory, it provides a free and comprehensive Google Analytics solution for targeting, reporting, cloud messaging, remote configuration, and other features.

    Once the project is created, we can move on to the next step: adding Firebase to our project.

    Create Our Firestore Database

    Having completed the creation of our Firebase project, we’ll move on to establishing our database. To do this, click on Firestore Database in the left-hand menu of our Firebase console.

    After clicking on Firestore Database, we’ll be redirected to the Cloud Firestore page. Here, click on the Create Database button.

    The next step involves defining our data structure. Firebase offers features to safeguard our data. Specifically, two security rules can be put in place: Production Mode and Test Mode. Both rules contribute to data security. For this tutorial, we’ll opt for Test Mode and click Next.

    A pop-up box will appear, prompting us to select our cloud storage location based on our geographic location.

    Next, we’ll create a new collection in our database to store our data. To start a new collection, click on the Start Collection button. You’ll then be prompted to create a Collection ID. Name this ID EmailCollection and click Next.

    Following this, we’ll create our first document. We’ll use the auto-ID feature, so click the Auto-ID button to generate an ID.

    newsletter vue firebase cloud firestore

    Our collection will then be created. To integrate Firebase into our web application, we’ll select the Project Overview option, which will return us to the Firebase project we initially created.

    Add Firebase to Our Web App

    Firebase can easily be integrated into various platforms, including iOS, Android, Web, Unity, and Flutter applications. Since we’re focusing on web applications, click on the third button that features a code symbol.

    newsletter vue firebase cloud firestore

    Next, we’ll register our app under the name newsletter-app. Firebase also offers us the option of hosting our application, which we’ll skip in this article. However, should you ever wish to host the program, it’s straightforward to return and configure this setting.

    Install and Set Up Firebase SDK

    The final step is to install and configure the Firebase SDK. To do so, run the following command to install Firebase.

     npm install firebase

    Once installed, copy the code provided and paste it into the file we created—NewsLetter.vue—within the script tag.

    import {
      getFirestore,
      collection,
      addDoc
    } from 'firebase/firestore';
    // Import the functions you need from the SDKs you need
    import { initializeApp } from 'firebase/app';
    // import { getAnalytics } from 'firebase/analytics';
    import { ref } from 'vue';
    const firebaseConfig = {
      // Paste your Your web app's Firebase configuration here
    };
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);

    You’ll notice a gap in the code; this is where we’ll insert the configuration file we copied. To obtain this file, click on Project Overview in the menu and then select Project Settings from the dropdown. This will navigate us to a page where we can copy our config file.

    newsletter vue firebase cloud firestore

    Design Our Newsletter Form with Tailwind CSS

    After setting up the Firebase SDK, our next step is to design the layout for our newsletter using Tailwind CSS. As mentioned in the prerequisites, you’ll need a basic understanding of Tailwind CSS to follow along in this section.

    Create a component called NewsLetter.vue and paste the provided code into it.

    <template>
      <section class="text-gray-600 body-font">
        <div class="container px-5 py-24 mx-auto flex flex-wrap items-center">
          <div class="lg:w-3/5 md:w-1/2 md:pr-16 lg:pr-0 pr-0">
            <h1 class="title-font font-medium text-3xl text-gray-900">Welcome to Trackee Newsletter</h1>
            <p class="leading-relaxed mt-4">Join our weekly newsletter. You'll also get some of our finest posts every week.
    </p>
          </div>
          <form class="lg:w-2/6 md:w-1/2 bg-gray-100 rounded-lg p-8 flex flex-col md:ml-auto w-full mt-10 md:mt-0 add"
            id="app">
            <h2 class="text-gray-900 text-lg font-medium title-font mb-5">Sign Up</h2>
            <div class="relative mb-4">
              <label for="full-name" class="leading-7 text-sm text-gray-600">Full Name</label>
              <input type="text"  name="name"
                class="w-full bg-white rounded border border-gray-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" >
            </div>
            <div class="relative mb-4">
              <label for="email" class="leading-7 text-sm text-gray-600">Email</label>
              <input   type="email" name="email"
                class="w-full bg-white rounded border border-gray-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out">
            </div>
            <button 
              class="text-white btn-bg border-0 py-2 px-8 focus:outline-none rounded text-lg">Send</button>
          </form>
        </div>
      </section>
    </template>

    A diagram illustrating what our application will look like is available for reference.

    newsletter vue firebase cloud firestore

    Integrate Cloud Firestore in Our Vue App

    Having designed our newsletter layout, we will next integrate Cloud Firestore into our Vue application. To do this, copy the following code and paste it into our component:

    import {getFirestore} from 'firebase/firestore';
    const db = getFirestore(app);

    When interacting with the database, Firestore employs four methods: Read, Create, Delete, and Update. In this section, we’ll focus on the Create method to add new data to our database.

    <template>
      <section class="text-gray-600 body-font">
        <div class="container px-5 py-24 mx-auto flex flex-wrap items-center">
          <div class="lg:w-3/5 md:w-1/2 md:pr-16 lg:pr-0 pr-0">
            <h1 class="title-font font-medium text-3xl text-gray-900">Welcome to Trackee Newsletter</h1>
            <p class="leading-relaxed mt-4">Join our weekly newsletter. You'll also get some of our finest posts every week.
    </p>
          </div>
          <form class="lg:w-2/6 md:w-1/2 bg-gray-100 rounded-lg p-8 flex flex-col md:ml-auto w-full mt-10 md:mt-0 add"
            id="app">
            <h2 class="text-gray-900 text-lg font-medium title-font mb-5">Sign Up</h2>
            <div class="relative mb-4">
              <label for="full-name" class="leading-7 text-sm text-gray-600">Full Name</label>
              <input ref="name" type="text"  name="name"
                class="w-full bg-white rounded border border-gray-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" >
            </div>
            <div class="relative mb-4">
              <label for="email" class="leading-7 text-sm text-gray-600">Email</label>
              <input ref="email"  type="email" name="email"
                class="w-full bg-white rounded border border-gray-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out">
            </div>
            <button @click.prevent="createNewSuscriber"
              class="text-white btn-bg border-0 py-2 px-8 focus:outline-none rounded text-lg">Send</button>
          </form>
        </div>
      </section>
    </template>
    


    We created two input fields in the preceding code sample to collect subscribers’ information. These fields request a name and email, each with a ref attribute. Next, we create a button with a click event to submit this information to our database.

    <script>
    import {
      getFirestore,
      collection,
      addDoc
    } from 'firebase/firestore';
    import { ref } from 'vue';
    export default {
      name: 'App',
      components: {},
      methods: {
        createNewSubscriber: function () {
          addDoc(collection(db, 'EmailCollection'), {
            name: this.$refs.name.value,
            email: this.$refs.email.value,
          });
        },
      },
      data: () => {
        return {
          subscribers: ref([]),
        };
      },
    };
    </script>
    
    • In the code, we import functions and objects from the Firebase library, specifically getFirestore, collection, and addDoc. These functions are used to create a new document in our Firestore collection.
    • Additionally, we import a ref function that allows us to create a reactive reference to an array of our subscribers.
    • We define a method property called createNewSubscriber that is triggered when a user submits new subscriber information. This method utilizes the addDoc function to add a new document to our Firestore collection, EmailCollection, pulling the name and email from the component’s $refs object.
    • We initialize a single file called subscribers as an empty array using the ref function. This data property will store our list of subscribers and make it reactive.

    This is an example of a diagram showing our empty database before users subscribe.

    newsletter vue firebase cloud firestore

    Here is full and working example of our application when a user subscribes to our newsletter:

    For easy access to the code examples see the Github link below it contains the demo link on the application description section.

    Conclusion

    In summary, Vue combined with Firebase Cloud Firestore provides a robust framework for building dynamic applications. Firebase Cloud Firestore offers a powerful server database system for storing and managing our data. In this tutorial, we explored both Firebase and Cloud Firestore, learning how to create an integrated application.

    One thought on “Creating a Newsletter Page With Vue and Firebase Cloud Firestore

    1. How to use Vue.js to create a form where users can enter their email addresses for the newsletter signup. This might involve using Tailwind CSS for styling (based on the previous search result).

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Avatar
    Writen by:
    Ezekiel Lawson is a software developer and technical writer. Aside from developing web tools and applications, he enjoys educating people and clarifying complex issues for easy comprehension by creating materials that will educate developers through technical writing.
    Avatar
    Reviewed by:
    I picked up most of my soft/hardware troubleshooting skills in the US Army. A decade of Java development drove me to operations, scaling infrastructure to cope with the thundering herd. Engineering coach and CTO of Teleclinic.