November 2, 2021 1 min read 289 words

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.jsexport const fireConfig= {// Place the json obtained as in// https://firebase.google.com/docs/admin/setup#initialize-sdk}

Create firebase.js

// File: lib/firebase.jsimport 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.jsimport 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 (opens in a new tab)

Thanks for reading

If this was useful, sharing it on X helps a lot. Spotted a typo or want to push back? DM me.

More posts

2 posts