DEV Community

Deepakshi Sood
Deepakshi Sood

Posted on

Authentication using Firebase for Express.js

Prerequisites: Express.js, Node.js, HTML

There are several ways to authenticate a Node.js app and I have found Google Firebase to be the simplest of all.
Authentication helps us to identify a user to securely save the data and provide a more personalized experience. It has easy-to-use SDKs and backend services that you can set up in minutes if you already have the web application backend running.

In this tutorial, I’ll be taking you through the steps to set up an email authentication for your Express.js web application.

1. Add Firebase Authentication

Image description

Sign in to your Firebase account and create a new project. Add a project ID associated with your project. Setting up Google Analytics is optional for the projects. You will be taken to the project console.

2. Register the app with Firebase and add SDKs to your app.js file

Image description

On the Firebase console page, click on the web icon(</>) to launch the setup. Provide a nickname to the app (enable Firebase hosting if required) and click on register. You will see a list of scripts that you need to add to the

. Instead of continuing with the step mentioned, copy the firebaseConfig object to a file.

// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "YOUR KEY",
authDomain: "YOUR PROJECT.firebaseapp.com",
projectId: "YOUR PROJECT ID",
storageBucket: "YOUR PROJECT.appspot.com",
messagingSenderId: "MESSAGING ID",
appId: "YOUR APP ID"
};

Click ‘Continue to console’.

On the console, go to Authentication > Sign-in method and make sure to enable Email/Password.

3. Add Firebase to your app.js file

In a terminal window at the location of your project, using npm to install firebase.

If you do not already have a package.json file, run the following command in your terminal.

npm init -y

Then, run

npm install --save firebase

Open your main Express.js file (usually called app.js) and require the firebase module and add your firebaseConfig object that we obtained above.

const firebase = require('firebase');
var firebaseConfig = {
apiKey: "YOUR KEY",
authDomain: "YOUR PROJECT.firebaseapp.com",
projectId: "YOUR PROJECT ID",
storageBucket: "YOUR PROJECT.appspot.com",
messagingSenderId: "MESSAGING ID",
appId: "YOUR APP ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

4. Add authentication to your Login/Register forms

Now, I assume you already have a form that users can submit with the fields Email and Password. If you do not, you can create a simple Register.html file as shown below. I have used Bootstrap in order to make the page look better. Three input fields: Username, Email, and Password are taken from the user.



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>
</head>
<body class="d-flex flex-column vh-100">
<h1 class="display-5">REGISTER</h1>
<br>
<form action="/register" class="validated-form" method="POST" novalidate>
<div class="mb-3">
<label class="form-lable" for="username">Username</label>
<input class = "form-control" type="text" name="username" id="username" required>
</div>
<div class="mb-3">
<label class="form-lable" for="email">Email ID</label>
<input class = "form-control" type="email" name="email" id="email" required>
</div>
<div class="mb-3">
<label class="form-lable" for="password">Password</label>
<input class = "form-control" type="password" name="password" id="password" required>
</div>
<button class="btn btn-secondary">Register</button>
</form>


Enter fullscreen mode Exit fullscreen mode

In your app.js file, obtain the email and password using the req object.

app.post('/register', async(req, res) => {
try {
const {email, username, password} = req.body;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
console.log(user);
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(error);
});
res.redirect('/');
} catch(e) {
res.redirect('register');
}
})

Once a user registers, he/she is also automatically signed in through firebase. You can go to your Project’s Firebase Console > Authentication > Users to view the registered users.

Image description

A middleware can be used to keep an account of the current user and store it in the local storage of your browser.

app.use((req, res, next) => {
var user = firebase.auth().currentUser;
res.locals.currentUser = user;
next();
})

Similar steps can be followed while logging in as a user and for logout purposes.

For login, create a similar form, then get the email, password from the req object.

app.post('/login', async(req, res) => {
const {email, password} = req.body;
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
var user = userCredential.user;
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
});
res.redirect('/');
})

For logout, you just need a route to log out.

app.get('/logout', function(req , res){
firebase.auth().signOut().then(() => {
res.redirect('/login');
}).catch((error) => {
// An error happened.
});
});

You can add multiple functionalities to the above tutorial, like sending an error flash message or redirecting to certain pages. The rest is to customize your application according to your needs.

Top comments (0)