Using Firebase Admin with Next.js

Rishi Raj Jain
/Tuesday, November 2 2021
Using Firebase Admin with Next.js

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
        . // set of operations
        .then(() => {
          res.status(200).json({ 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 Next.js. 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

Dynamic Previews with Next.js, TailwindCSS, Chrome AWS Lambda and Layer0