Hackernoon logoHow To Capture Email On Static Websites? by@jakeschmidt

How To Capture Email On Static Websites?

Author profile picture


Comp sci and cyber security

One of the first dynamic features that you may want to add to your website is an email sign up form. Email sign-ups come in handy for maintaining contact with potential clients or simply those who are interested in reading your blog/website. In this tutorial, I will cover how to add an email capture section to your website even if you host your site statically on something like github.pages. 
This feature uses Google firebase which for low traffic databases is entirely free. The first part of setting up an email sign up form is to get a front end established so that visitors to your site can enter their email into a form and can have it sent to the database.
Setting up the front end
Below is the HTML, CSS, and javascript for a very basic email capture section. Feel free to use this example or your own, whatever works best for you. The HTML and CSS below are fairly self-explanatory and change the look of the form. If you choose to not use this format you may want to look at the javascript in order to see how we are sending the email as a json object to firebase. This code pen contains everything needed for the front end.
Setting up the Real Time Database
1.Next, we will cover how to configure and set up your Google firebase account. Firebase's Real Time database features require that you make a Gmail account. Once this part is finished we will log in to firebase and create a new project.
2. Name your project, accept the terms, and continue on to the next steps
3. We will be creating a web application in this tutorial so go ahead and select a new web application.
4. Register a name for your application.
5. Copy the lines that firebase generates for you and insert them below your HTML in your webpage or in a separate javascript file. The code generated should look similiar to the image below. This part configures the firebase database with your webpages and then initializes the firebase app. There is one more script we need to include in order for this to work so don't forget to also include this before you include the code from firebase:
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>
6. Now that we have a project we are going to need to create a database to hold the emails. Google firebase offers two types of databases, the cloud firestore, and Realtime database. We are going to use the Realtime database due to its simplicity in storing .json data and that we won't be doing any complex queries. Both databases would work for this project but for the remainder of this tutorial, we will use Realtime database. 
7. Later we will be changing the rules for our database to filter out invalid email addresses but for now, we will set .
both to true in order to more easily verify our work. It is important to go back and change these rules later otherwise anyone can read/write/modify all of the data in the database. For now, it should look similar to the image below for your rules.
Setting up the Javascript for the database
The javascript that's listed below is fairly important as it will handle all of the work for adding the emails to our database. This is the same javascript that is in the codepen above, but I feel it's important to understand what it does. The first thing we need to worry about is checking whether emails are valid or not before we add them to our database. This is handled by a function in the javascript that compares the email with a regex to match with emails proper format. After its validated the email is either sent to the database and the form is cleared or a rejection div appears and nothing is sent to the database. We will also be validating the emails in our database rules, covered later.
function saveToFirebase() 
    const data = document.getElementById('emailForm').elements[0].value;

    database.ref('emails').push({ email: data}).then(function(snapshot) {
      pass(); // some success method
      }, function(error) 
            console.log('error' + error);
            fail(); // some error method


function ValidateEmail(mail) 
    if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(mail))
          return (true);
          return (false);

function fail()


function pass()

The above code is fairly simple but below I’ll explain what each part is doing overall.
  • SavetoFirebase
    grabs the email string from the form, and passes it to a regex check. If the email passes the check, then it is sent to the
    and we pass it as a json
    object {email : data }
    with the
  • The
    function is a regex check to make sure its an email that was entered.
  • The last two functions are only to signal to the user that their email was either accepted or rejected by the database. This has a somewhat smooth transition to make the correct divs appear whether its
Go ahead and launch your website locally or live. Type in a valid email address in your form. If you look under data in the Realtime database console you’ll see that under
a random primary key is assigned to the email object you entered. Don’t worry too much about the random keys right now, when we cover how to fetch the emails, we will filter out the keys.
    "rules": {
      // write is allowed for all paths
      ".write": true,
      "emails": {
    		"$emailid": {
          ".read": "auth != null",
   				".write": "auth != null",
        ".validate": "newData.hasChild('email')",
          "email" :
            ".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)"
        ".read" : true
The rules are highly important here as we need to only allow users to send email addresses to the database. I’ll be brief here in my explanation but I highly recommend reading googles documentation on security and validating data if you're interested in designing more complex rules.
Basically we are just checking that the json objects that are pushed to the database contain an email field and then validate that those strings are in fact valid emails. Lastly, we changed the
ability to true for our next steps in reading data from the database. 
How to collect the emails from your database
By this point you should have your data all set in the realtime database and your website correctly captures emails that are sent to the database. The hard part is over and now we simply want an easier way to see all of the emails that are being stored in the database.
This script uses node.js so we will cover the basics of installing node on Linux and the proper packages to successfully pull the emails. If you don't have node.js installed already then we will need to install it. You can check by typing in the terminal
$ node -v 
If not installed then type:
$ sudo apt install nodejs
Next install node package manager if you don't already have it. Check with
$ npm -v
$ sudo apt install npm
Now create a directory that you want to hold the script and all of the files that the script will pull from the database. I called mine emailData
You can do this from the terminal with
mkdir emailData
Now navigate to the directory in your terminal. Once in the correct directory we need to create
file, this can be done by typing
$ npm init 
then by following the prompts.
Next, we need to install the firebase admin package with the terminal by typing
$ npm install firebase-admin --save
Now we need to download a new private key for our database. Going back to our firebase console we need to navigate to project settings and find “service accounts” here we will “generate new private key” be sure to copy the path that it downloads the private key to, we will need this path for our script. Usually something like this.
Replace line 7:
var serviceAccount = require("here!");

in the following code with the path to your service account key. 
Lastly, replace line 11:
databaseURL: "https://emailexample-a624c.firebaseio.com"
, in the following code with the database URL for your database. This can be found on the service accounts page where the private key was generated. 

var admin = require("firebase-admin");
const fs = require('fs');

// you will need to download a key and replace this path
var serviceAccount = require("/home/user/Downloads/serviceaccountkey.json");

  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://myappurl.firebaseio.com",
  databaseAuthVariableOverride: null

var db = admin.database();
var ref = db.ref("/emails");
ref.orderByChild("email").on("value", function(snapshot) {

let info = snapshot.val();
let data = JSON.stringify(info,null,2);
fs.writeFileSync('emails.json', data);
}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);

let writeStream = fs.createWriteStream('emails.txt');

function parseMe(obj)
  var keys = Object.keys( obj );
 for( var i = 0,length = keys.length; i < length; i++ ) {
     console.log(obj[ keys[ i ]].email);
     writeStream.write(obj[ keys[ i ]].email +"\n");
Now save this script to your directory, and name it, I called mine “
Now you should be able to type :
$ node firebasescript.js

you'll see that directly on the terminal it shows all of the emails in your database. It also generates two files one .txt and one .json. The .txt is a file with all of the emails in a list form and the other is the emails in their .json form. 

Should be all finished up and now we have an email collection front end and realtime database using google's firebase. We have also created a script to grab all of the emails in our database. This is a fairly simple example and by no means is the most secure or effcient way to make an email collection database, but its simple, free, and only takes about ten minutes to set up.


The Noonification banner

Subscribe to get your daily round-up of top tech stories!