I will be going through a very basic app setup. A node backend with a vue frontend. If you already have your back and front end setup and just need the Firebase Auth part, skip to here.

If you just want the code example, hey I get it. Here you go.

The Node.js backend

You will need to have node and npm installed. If you do not, you can do so here: https://nodejs.org/en/

We will create our basic app from the express-generator. Open your terminal and go ahead and install it with npm i -g express-generator . Now create a folder, mkdir fbAuthDemo and go into it, cd fbAuthDemo . Now use express-generator to create our node backend express server . Now open that in your text editor, for me code . . You should see something similar to this:

The vanilla express app

Right off the bat, let’s delete the public/ , routes/ , and views/ folders, we wont need them. You can also delete the app.use(<route>, <func>) calls, as well as the error handlers, view engine setup calls, and all now-unused imports. Your app.js should now look like:

Now we will add one basic route:

We can test this by running our app ( npm install && npm i nodemon if you have not already), then DEBUG=server:* nodemon start . Then hit the endpoint in Postman, curl, or your browser by hitting the http://localhost:3000/ route. You should get back:

Our first response

Finally, let’s add a dummy function for authorization, which we will fill in with Firebase’s logic later. We will add a dummy authorized boolean and use it in some custom middleware to check authentication. If the user is authorized, we will move on, and if not, we will send back a 403: Unauthorized . Above app.get(..) :

You should now be able to access the route when authorized = true , and be blocked when authorized = false .

One last thing before we move on the the front end, we will need to add cors so that our front end will be able to talk to the backend. It is very easy, just npm i cors , then add these two lines to your app.js:

Our final app.js file should look like:

The Vue.js frontend

Feel free to use any front end, but since Vue is much more pleasant to work with, I will be using it.

We will get started in a similar fashion to the backend. In your terminal go the the fbAuthDemo/ folder we created. We are going to use the vue cli to instantiate our project so if you do not have it, npm i -g @vue/cli . Then you can vue create client . I pick options manually, and usually go with only Babel, and put it in the package.json, for simplicity. After vue cli completes, we will go into the client folder cd client and open it in our code editor code . . It should look something like

Our vanilla Vue project

We can go ahead and run this in the terminal with npm run serve , and checkout the default page

The default vue project page

We don’t need all those links, so lets head over to src/components/HelloWorld.vue and strip them out. We will get rid of everything in the main <div> below the <h1>{{ msg }}</h1> tags. Then lets add a button and p tag of our own

You should notice two things: We are using bootstrap classes, and we are referencing a variable response that we have yet to define. Let’s define the variable first, then add bootstrap to our project, just so things look nice.

To add the response variable, we will need to give our Vue component a data property. Now remember, it needs to be a function (I spent too long on this).

Now head over to public/index.html , and add Bootstrap’s CDN link to the header:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Now everything should look nice and we have all the variables to display our data. But what about that Send Request button? Well let’s create a method in our Vue component, and bind it to our button. What is that method going to do? Send a request of course! Let’s use axios to do that. Go ahead and npm i axios to your project and then in the script tags of the Vue component we can import axios and create a client with it.

Then we will create a method in our view component to use this client to send a default get request to the / blank route. This method should store the message from the axios call into our Vue component’s response data variable on success, and store the error instead on failure.

Now we will bind this to our button:

<button @click="sendRequest" class="btn btn-outline-success my-4">Send Request ></button>

Our final HelloWorld.vue file at this point should look like:

Now, if we run our server as before DEBUG=server:* nodemon start , and our client as before npm run serve , we should see that we get ‘Hello World!’ back from our server and displayed for us:

If you get the ‘Error: Request failed with status code 403!’ instead, that is because you left your dummy authorized variable in the server set to false . So switch it back and test that it works. Or, switch it to false and see that the dummy authCheck function works. Either, way, we are now ready to implement the Firebase Authentication on our custom backend!

Adding Firebase Auth to our custom backend

If you followed along with the first two parts, you should have a working backend connected to your working frontend. Or, if you have your own backend and frontend setup and connected, that will work just as well, as long as Firebase is supported in the languages you used to do so. (It probably is) You may just have to change these instructions slightly (perhaps you are using pip, not npm, and your code will look different just check the docs, etc)

First things first, go to firebase and create a new project. Call it what you like, and I recommend not using Google Analytics, there is no point for this project. Once done, we need to add this to our Vue and backend. Why both? Well…

In order to test this, we will have to use Firebase Auth to login a user to our front end, get a AuthToken for that user, then send that token to our server and use Firebase Admin to verify that token. So both the frontend and backend need to be using Firebase. So let’s add it to our frontend first, and get a dummy user logged in.

Firebase Auth on the frontend

First, npm i firebase in our Vue project. Then go to main.js and import it with import firebase from 'firebase' .

Click on the </> icon on the front page of your firebase app, and create a client project.

Add a client project first

Once it finishes, you should be presented with a config file. Go ahead and copy the part that looks similar to

{

apiKey: "AIzaSyBqLUasFAKEBvY94anzYi1P1o19DKs",

authDomain: "fbauthdemo-2a451.firebaseapp.com",

databaseURL: "https://fbauthdemo-2a451.firebaseio.com",

projectId: "fbauthdemo-2a451",

storageBucket: "",

messagingSenderId: "839675573680",

appId: "1:839675573680:web:b7e921f299469934659275"

}

Then head over to our Vue project, go to the main.js file where we imported firebase and we can initialize our firebase app in Vue with

firebase.initializeApp({

apiKey: "AIzaSyBqLUXaDFAKEY94anzYi1P1o19DKs",

authDomain: "fbauthdemo-2a451.firebaseapp.com",

databaseURL: "https://fbauthdemo-2a451.firebaseio.com",

projectId: "fbauthdemo-2a451",

storageBucket: "",

messagingSenderId: "839675573680",

appId: "1:839675573680:web:b7e921f299469934659275"

})

Now let’s create that dummy user. Head back to Firebase and click ‘Continue to console’ if you aren’t there already. Now on the sidebar, choose ‘Authentication’, and then in the middle click ‘Setup sign-in method’. Next you can choose Email, and enable it (Not the email passwordless link part). Now that that is enabled, go back to ‘Authentication’ and on the right, click ‘Add user’. Fill in some dummy data and remember it, because we are going to hardcode it into our app. I am going to use ‘dummy@gmail.com’ and ‘pass123!’.

Obviously if you have your own front end or are going to make this a real app, add actual user registration and login, don’t hardcode it. But this is just for demo purposes.

Let’s go to the Vue app and add a way to sign in. First, import firebase. Next, let’s create two methods, signIn , and signOut , as well as another data variable and p tag to display that status.

Now lastly, if the user is signed in, we want to add the AuthToken to the request headers.

...

firebase.auth().currentUser.getIdToken(true)

.then((idToken) => {

client({

method: 'get',

url: '/',

headers: {

'AuthToken': idToken

}

...

Complete Vue app code

Our complete Vue app

Now that our front end is done, whether we are Signed in or not, we should get the same response from the backend, depending on whatever the authorized dummy variable is. Let’s go change that and use real Firebase Admin validation on the backend.

Firebase Admin on the Backend

Now we can finally get to the meat of the tutorial! Let’s get rid of the dummy data and use firebase to check the authorization of our requests! First, let’s npm i firebase-admin to our server project. Then import it to our app.js const admin = require('firebase-admin') .

Next, we will need a service acount for our project. Go to your firebase console, click the settings icons on the left, and select ‘Project settings’. Then go to the ‘Service Accounts’ tab. There, we will click ‘Generate new private key’, and store it in our client project under config/fbServiceAccountKey.json . NOTE: Do not upload this to github, or share it publicly.

Next, we can copy the code they give us to initialize the admin app, replacing the dummy path with our real path where we stored the key.

const serviceAccount = require("config/fbServiceAccountKey.json"); admin.initializeApp({

credential: admin.credential.cert(serviceAccount),

databaseURL: "https://fbauthdemo-2a451.firebaseio.com"

});

Your’s ought to be slightly different because your app is not my app. So your database URL will be different.

Now instead of checking the dummy variable in our checkAuth() function, let’s use firebase to check the AuthToken in request headers. First, we check that it exists, and if so, we use Firebase Admin to verify it. If it comes back verified, we move on, otherwise we return a ‘403: Unauthorized’.

Our code is complete! Our final app.js should look like:

Now, if we run our server as before DEBUG=server:* nodemon start , and our client as before npm run serve , we can test the authentication check! If we click ‘Sign In >’ on the front end, and then hit ‘Send Request >’, we get our Hello World message successfully! And if we then click ‘Sign Out >’ and then try to hit ‘Send Request >’, we will get our 403: Unauthorized!

Success!

If you made it all the way, congrats, and I hope this helped. This is my first Medium article, and man it took longer than I thought! Claps are appreciated I guess, and if you need the source code, check my github for ‘fbAuthDemo’. And I may add a video tutorial to this as well here soon! Til next time…