Firebase Authentication With Custom Node.js+Express Backend

Wanuja Ranasinghe
Dev Genius
Published in
10 min readSep 22, 2022

--

Firebase Authentication With Custom Node.js+Express Backend
Firebase Authentication With Custom Node.js+Express Backend

In this article, I explain how to integrate Firebase Authentication to React, Node.js, and Express applications. When we use firebase authentication, we usually use Cloud Firestore as a database and don’t need a backend. On the other hand, you should have a proper idea about firebase security rules to protect your data. But in this article, I use node express backend. So, if you are trying to integrate firebase authentication with a custom backend, I’m pretty sure this article will help you greatly. And you can use the entire source code from here.

Mainly we can divide our process into three steps,

Step 01: Firebase authentication in react application. After authentication, firebase will send you a user object withholding the JWT token.

Step 02: Then we can use that JWT token to send API requests to our backend.

Step 03: Then the backend can use that JWT token to verify the user from firebase, if the user is validated, we can send data to the frontend otherwise we can ignore the request received from the front-end.

So, let’s dive into the content.

01) Create a ReactJS application.

02) Create a Firebase project in the firebase console and activate authentication.

03) Add and initialize the Authentication SDK in react app.

04) Google Authentication in the front end.

05) Create backend(node+express) application.

06) Retrieve data from the front end.

07) Firebase Admin SDK Configuration in the backend.

08) Create middleware to validate the access token.

01) Create a ReactJS application

As all of you know I’m starting with the “npx create-react-app your_app_name” command. Then by running the “npm run start” command, you can see our react application is running at localhost:3000.

02) Create a Firebase project in the Firebase console and activate authentication

  1. Now go to https://firebase.google.com/ and go to the firebase console. If you don’t have a firebase account, make sure to create an account before moving into the next steps.
Get started with firebase

2. Now create a new project and give it the name you want.

Creating a new project in firebase
Creating a new project by giving a project name

3. Next, they will ask to enable google analytics to your firebase project and here you can choose an option as you want. After that create the project.

Enabling google analytics in the firebase project

4. Then you will be redirected to the project dashboard and now we need to create an app. Here you can create an IOS, Android, or Web application, since we are going to use the ReactJS application I choose a web app.

Chose application type

5. After that, register your app by giving a name.

Registration of firebase application

6. After that you will receive a firebase SDK details as below.

Firebase SDK

7. Now we need to install the firebase npm package to react application. open your terminal and run the below command.

npm install firebase

8. After that copy the SDK firebase config details from the above step and then continue to the console.

9. Then again you will redirect to the dashboard and then select the Authentication tab.

Authentication

10. Now we need to choose and enable the sign-in methods that we need to integrate into our app. Here I’m choosing the Google signing method for demonstration. (Here you can select any number of sign-in methods according to your requirement.)

Select the Google Sign-in method

11. In the next step enable that sign-in method by giving proper “Project public-facing name” and “Project support email”.

Google sign-in configurations

Cool, now we have set up everything in firebase, and now we need to add firebase auth to our react application.

03) Add and initialize the Authentication SDK in react app

1. Create a folder called “config” under the “src” folder and, inside that config folder, create a firebase-config.js file to add firebase SDK configurations. The below image shows my folder structure up to now.

Folder structure — 1

2. Then Copy and paste the firebase configurations into the firebase-config.js file.

If you forgot to copy the above code segment in the previous step, you can get it by following the below steps.

Select project settings -> Select general tab -> Then scroll down until you get SDK setup and configuration.

3. Now import that firebase-config.js file into index.js.

4. From now we need to follow firebase documentation step by step. I always recommend you follow official documentation with these helpful tutorials. https://firebase.google.com/docs/auth/web/google-signin

In the app.js file remove unnecessary things and add a simple button like the one below.

The initial step in app.js

04) Google Authentication in front-end

Now follow the below steps and do the necessary changes for app.js

Step 01: Create an instance of the Google provider object:

import {GoogleAuthProvider} from ‘firebase/auth’const provider = new GoogleAuthProvider();

Step 02: Specify additional OAuth 2.0 scopes that you want to request from the authentication provider.

provider.addScope(‘https://www.googleapis.com/auth/contacts.readonly');

Step 03: Create an auth instance

import { getAuth } from "firebase/auth";
const auth = getAuth();

Step 04: Now copy the below code into the app.js

signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});

After following the above steps, the app.js file will look like this.

Note: I have created a separate method called signInwithGoogle to call when I click the sign-in button.

Now in the browser click that sign-in button and check whether you can sign in or not. If you could not sign in, check the Source Code and check your mistakes.

Step 04: Now store the access token in session storage.

After the user is signed in, extract the access token, and set it in the session storage. And here I also use a useState to track the authentication status of the user.

const [authorizedUser,setAuthorizedUser] = useState(false || sessionStorage.getItem("accessToken"));

Inside the signInwithGoogle method

if(user){user.getIdToken().then((tkn)=>{// set access token in session storagesessionStorage.setItem("accessToken", tkn);setAuthorizedUser(true);})}

Now what I’m going to do is, after authorizing the user I’m going to show a string (“Authorized User”). This string is visible only when the user is signed in.

Inside the render method,

<div className="App">{authorizedUser ? (<><p>Authorized user</p></>): (<><button onClick={signInwithGoogle}>SignWithGoogle</button></>)}</div>

After following the above steps and creating the logout function, our app.js will look like this.

Now let’s move to the backend.

05) Create backend(node+express) application.

In the root folder, I have created a new folder called ‘backend’ and inside this folder, create the package.json file using the following command.

npm init

After that install express, cors, nodemon, and firebase-admin dependencies by using the following command.

npm i express firebase-admin cors nodemon

Then after that in the root directory, I’m creating a index.js file and inside that file, I’m creating our basic express application.

After that add below two script commands into the package.json file.

"scripts": {"dev": "nodemon index.js","start": "node index.js"},

Now you can check whether this application is running by using the below command, and the server will run on port 5000.

npm run dev
localhost:5000

Inside the index.js, I’m creating a new endpoint ‘/api/tasks’ to send a set of tasks (array of JSON objects).

06) Retrieve data from the front end.

Now let’s go back to the react application and retrieve those data(tasks).

To send requests to the backend endpoint, we need to install the Axios npm package. By using the below command install the Axios in to react application.

npm install axios

For more readability I’m creating a separate component (Tasks.jsx) to show these tasks, Inside the Tasks component, I’m doing the following things to retrieve data from the backend.

01) First import the Axios.

02) Pass the access token to the Tasks component through the props.

03) Create a method to fetch the data from the backend by sending an authorization header.

04) Calling the declared method from inside the useEffect hook.

05) Storing retrieved tasks in a useState.

06) Finally using the map function, we are going to display tasks.

After following the above steps our Tasks component will look like this.

Then import this component to the app.js file with the passing access token as a prop.

If you go back to localhost:3000 you may see the tasks that we retrieved from the backend.

Now what we need to do is, we need to protect our backend routes. As you can see, in the last step we were able to directly access the ‘/api/tasks’ route. So, we need to authorize the user before sending the data to the front end. To do that we need to create a middleware. As I mentioned earlier, when the client sends the request with an access token, we authorized the token from the backend by with communicating firebase.

07) Firebase Admin SDK Configuration in the backend.

Go to the firebase console and click the project settings. Then select the service accounts tab. Then you will see the Admin SDK configuration snippet. From that select node.js and copy the snippet.

Note: In the next step we have to generate a new private key, so don’t close the tab.

Firebase Admin SDK Configuration in the backend

Inside our express application(backend) I’m creating a firebase-config.js file as below.

Backend folder structure — 1

After that inside that firebase-config.js file, paste the copied code snippet in the previous step. Then export that module as we usually do.

Now again go back to the firebase console and generate a new private key. Then download that JSON file into your backend. I have downloaded it into the Backend/src/config directory, and I have renamed it as ServiceAccount.json.

Backend folder structure — 2

Note: This ServiceAccount.json file has confidential details about your firebase project. So, when you are deploying or when you push to GitHub don’t forget to add it into .gitignore.

08) Create middleware to validate the access token.

Create a folder called middleware inside the src folder in the backend. Inside that folder create another file called index.js.

Copy and paste the below code inside that file.

Explanation of line 4: If we observe the authorization header that we are sending from the front-end, its looks like this.

authorization: ‘Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6………..’

So, we need to extract the access token from this string. To do that first we split the string from space (‘ ’), then we will receive an array like this.

[‘Bearer ’, ‘eyJhbGciOiJSUzI1NiIsImtpZCI6………..’]

From that, we need to pick up the second element to get the token.

Explanation of line 4: By using firebase admin verifying the token

Explanation of lines 7–10: If the decoded value is valid, the next process will be allowed.

Explanation of line 12: If the decoded value is not valid, the next process will be terminated, and it will throw an error.

As a final step, we need to call this middleware in our index.js file. Here I have called this middleware as a global middleware, which means when we are trying to hit any endpoint, this middleware will be triggered and checks whether the access token sent by the frontend is valid or not. If it is valid, the relevant request will be allowed.

const middleware = require('./src/middleware/index');
app.use(middleware.decodeToken);

Booom!! We’ve done it. After receiving data from the backend you can see our react application like this.

Authorized user view

Conclusion

That’s how you can integrate the firebase authentication into react node express application. Hope it was worth reading, and if it is so, please consider sharing this article on social media, if you have any suggestions, please leave a comment. I love to hear from you.

Thanks for reading ❤️.

If you enjoyed this article you can support me through Buy me a coffee.

Buy me a coffee

Source code

https://github.com/Wanuja97/firebase-authentication-with-react-node-express-article

References

01) Official Firebase documentation — https://firebase.google.com/docs/auth/web/google-signin

--

--