---
title: Using Firebase Admin with Next.js
description: Trying to set up firebase-admin with Next.js with no success? Read the solution I reached after doing several deployments.
url: https://rishi.app/blog/using-firebase-admin-with-next-js
author: Rishi Raj Jain
published_at: 2021-11-02T09:06:31.120Z
updated_at: 2026-10-14T22:26:37.602Z
---

# Using Firebase Admin with Next.js

## Initialize Next.js Starter
```bash
npx create-next-app project-name
```

## Install firebase-admin
```bash
npm install firebase-admin
```

## Generate the firebase config
```js
// 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
```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
```js
// 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](mailto:rishi18304@iiitd.ac.in). Find my portfolio's code at [rishi-raj-jain/rishi.app](https://github.com/rishi-raj-jain/rishi.app)

---

This is the Markdown version of https://rishi.app/blog/using-firebase-admin-with-next-js. Every page on this site is listed with a summary at https://rishi.app/sitemap.md.
