DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on • Originally published at rishi.app

Using Firebase Admin with Next.js

Initialize Next.js Starter

npx create-next-app project-name
Enter fullscreen mode Exit fullscreen mode

Install firebase-admin

npm install firebase-admin
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
        })
    }

}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)