Tuesday, November 2 2021

Using Firebase Admin with Next.js

Rishi Raj Jain
Rishi Raj Jain @rishi_raj_jain_

Initialize Next.js Starter

npx create-next-app project-name

Install firebase-admin

npm install firebase-admin

Generate the firebase config

// File: lib/fireConfig.js

export const fireConfig= {
// Place the json obtained as in
// https://firebase.google.com/docs/admin/setup#initialize-sdk
}

Create firebase.js

// File: lib/firebase.js

import admin from 'firebase-admin'
import { fireConfig } from './fireConfig'

try {
  admin.initializeApp({
    credential: admin.credential.cert(fireConfig),
  })
  console.log('Initialized.')
} catch (error) {
  /*
   * We skip the "already exists" message which is
   * not an actual error when we're hot-reloading.
   */
  if (!/already exists/u.test(error.message)) {
    console.error('Firebase admin initialization error', error.stack)
  }
}

export default admin

Use firebase-admin in Next.js API Routes

// File: pages/api/tryFirebaseAdmin.js

import admin from '@/lib/firebase'

export default async function handler(req, res) {
    const firebase = admin.firestore()

    // Return promise to handle serverless function timeouts
    return new Promise((resolve, reject) => {
       firebase
        // For example, look into the comments collection
        .collection('comments')
        .get()
        // set of operations to perform on the collection's records
        .then((posts) => {
          res.status(200).json({ comments: posts.docs.map((doc) => doc.data()) })
          res.end()
          resolve()
        })
        .catch((e) => {
          res.status(405).json(e)
          res.end()
          resolve()
        })
    }

}

Example

This page itself obtains data from server side data fetch with firebase-admin and Astro. Feel free to add any problems in comments, or email me at rishi18304@iiitd.ac.in. Find my portfolio's code at rishi-raj-jain/rishi.app

Write a comment

Email will remain confidential.