How to use Firebase in your Next.js Project

Stewart Granger Flores - 15 Noviembre, 2020

Firebase Banner

1.- Creating your project

In order to use Firestore/Firebase in your Next.js project we will take advantage of the ability to create Next.js Lambda functions, but let's take it one step at a time. The first thing we will do is to create a Firebase project. To create a Firestore DB we need to go to Firebase and click on Go to the console in the upper right corner and click on Add Project.

When you finish selecting your project's analytics needs, we'll move on to the Firebase dashboard.

1.1 Creating our Firestore DB

Now we will go to Cloud Firestore, you can get there by clicking on the left menu and we will start creating our database.
Firebase Create Project
A message will pop up giving us a choice between Production or Test and we will select one of them
Personally, I recommend starting as Production despite being in a test environment.
We will create the DB in the closest server to us, in my case, SouthAmerica.
Firebase Locale Selection

2.- Associating an application to our Firebase project

In order to continue, we need to associate an application to this project. To do this we will go to the project configuration by clicking on the nut and clicking on Configuration.
Now in the configuration we will go to the tab Service accounts where we will be given the credentials to log in and use our application in Next.js by clicking on Generate new private key.

What is the private key?

It is a Json document that Firebase gives us to configure our application and connect to Firestore from our Next.js project.
Note: These data is PRIVATE and must be treated with care, so to make use of them we will use the environment variables that allow us to use both the project and Vercel.

When the file is downloaded we will see something similar to this 👇🏻
  
    {
        type: "",
        project_id: "",
        private_key_id: "",
        private_key:"",
        client_email:"",
        client_id: "",
        auth_uri: "",
        token_uri: "",
        auth_provider_x509_cert_url: "",
        client_x509_cert_url:"",
   }
   

This is where we will get the values of our environment variables.

3.- Create Firebase configuration

Now with the necessary keys to configure our project, we will create a file in our project root path named .env.local. Here we will write only the data we need:



    FIREBASE_PROJECT_ID = "test-project"
    FIREBASE_CLIENT_EMAIL = "firebase-adminsdk-ejobd@test-project...eaccount.com"
    FIREBASE_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-..."

Once this data is created, we can use it in our Lambda functions.

3.1.- Create Firebase Configuration

In order to use this configuration we need to install the firebase-admin NPM package, so we will do the following


    npm install firebase-admin --save
        

We create a folder in the root of the project called lib and inside the lib folder we create a file called firebase-admin.js


Firebase location

Here inside we can paste this base configuration


    var admin = require("firebase-admin");

    try {
      admin.initializeApp({
        credential: admin.credential.cert({
          project_id: process.env.FIREBASE_PROJECT_ID,
          private_key: process.env.FIREBASE_PRIVATE_KEY,
          client_email: process.env.FIREBASE_CLIENT_EMAIL,
        }),
        databaseURL: "https://test-project.firebaseio.com",
      });
    } catch (error) {
      if (!/already exists/u.test(error.message)) {
        // eslint-disable-next-line no-console
        console.error("Firebase admin initialization error", error.stack);
      }
    }

    export default admin.firestore();
    

Note: the databaseURL is in the service accounts window we accessed in the first step.

Ready :)

Now we can use in our Lambda endpoints the database we created in Firestore by importing in our NodeJs environment from Next.js located at /pages/api


    import db from "../../../lib/firebase-admin";