DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on • Originally published at rishi.app

8 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay