Using Firebase Auth in Node.js: The Complete Guide

Updated: January 21, 2024 By: Guest Contributor Post a comment

Introduction

Integrating Firebase Auth into a Node.js application is essential for developers who need to manage user authentication with minimal hassle. This guide offers a step-by-step approach to using Firebase Auth in conjunction with Node.js, complete with code examples to illustrate the process. By the end of this guide, you’ll have a clear understanding of how to authenticate users and manage sessions securely in your Node.js apps using Firebase Auth.

Setting Up Firebase Project

Before diving into the code, you must set up a Firebase project. Go to the Firebase Console, create a new project, and follow the setup instructions. Once the project is created, navigate to the Authentication section and set up the sign-in methods you’d like to use.

Installing Firebase SDK

npm install firebase-admin --save

This command will install the Firebase Admin SDK, which is necessary for server-side operations.

Initializing Firebase in Node.js

To initialize Firebase, you’ll need a private key file for your Firebase project. Generate this key from the Firebase Console (‘Project settings’ -> ‘Service accounts’ -> ‘Generate new private key’). Store this file securely and use it as shown below:

const admin = require('firebase-admin');

const serviceAccount = require('./path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

User Authentication Flow

Sign up Users

To sign up users, you’ll need to create new users with an email and password. Here’s an example of how to do it:

admin.auth().createUser({
  email: "[email protected]",
  password: "secretPassword",
}).then((userRecord) => {
  console.log('User created:', userRecord.uid);
}).catch((error) => {
  console.log('Error creating user:', error);
});

Sign in Users

Once you’ve signed up users, signing them in involves verifying their credentials and returning a custom token that they can use for session management:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.post('/login', (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  admin.auth().getUserByEmail(email)
    .then((userRecord) => {
      // Implement password verification for your user, 
      // and if successful provide a token
      /* ... */
    })
    .catch((error) => {
      res.status(401).send('Auth failed');
    });
});

Managing Sessions and Auth State

Once a user has signed in, you need to manage their session. The following code snippet uses Firebase’s session cookies combined with Express middleware to verify session cookies and protect routes:

app.post('/sessionLogin', (req, res) => {
  const idToken = req.body.idToken.toString();
  admin.auth().createSessionCookie(idToken, { expiresIn: 60 * 60 * 24 * 5 * 1000 })
    .then((sessionCookie) => {
      const options = { maxAge: 60 * 60 * 24 * 5 * 1000, httpOnly: true, secure: true };
      res.cookie('session', sessionCookie, options);
      res.end(JSON.stringify({ status: 'success' }));
    }, error => {
      res.status(401).send('UNAUTHORIZED REQUEST!');
    });
});

app.use((req, res, next) => {
  const sessionCookie = req.cookies.session || '';
  admin.auth().verifySessionCookie(sessionCookie, true)
    .then(() => {
      next();
    })
    .catch((error) => {
      res.redirect('/login');
    });
});

Conclusion

The integration of Firebase Auth with Node.js enables developers to easily authenticate users and manage sessions, ensuring a secure, seamless user experience. Remember, Firebase Auth’s rich set of features goes well beyond email and password authentication; it also supports various sign-in methods, such as OAuth providers and phone authentication, giving you the flexibility to address a wide range of use cases.

Note: Always be sure to update your Firebase and Node.js packages frequently to take advantage of the latest security patches and features. With Firebase Auth, Node.js developers have access to a robust authentication system that is constantly evolving, with support provided by Google’s strong security frameworks and best practices.