---
title: Using Firebase Admin with SvelteKit
description: Trying to set up firebase-admin with SvelteKit with no success? Read the solution I reached after doing several deployments.
url: https://rishi.app/blog/using-firebase-admin-with-sveltekit
author: Rishi Raj Jain
published_at: 2022-12-21T21:59:00.000Z
updated_at: 2026-10-14T22:26:37.602Z
---

# Using Firebase Admin with SvelteKit

## Initialize SvelteKit Starter
```bash
npm create svelte@latest my-app
cd my-app
npm install
```

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

## Generate the firebase config
```js
// File: src/routes/fireConfig.js

import * as dotenv from 'dotenv'
dotenv.config()

// Load the env variables per SvelteKit
// https://kit.svelte.dev/docs/modules#$env-dynamic-private 
import { env } from '$env/dynamic/private'

export const fireConfig = {
	projectId: env.FIREBASE_project_id,
	privateKey: env.FIREBASE_private_key?.replace(/\\n/g, '\n'),
	clientEmail: env.FIREBASE_client_email
}
```

## Create firebase.js
```js
// File: src/routes/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 SvelteKit API Routes
```js
// File: src/routes/api/comments/+server.js

import admin from '../../firebase'
import { json } from '@sveltejs/kit'

// More on why use event driven api routes
// https://kit.svelte.dev/docs/routing#server-receiving-data
export async function GET({ request }) {
	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) => {
				// Resolve the promise in the GET route
				// with comments as json
				resolve(
					json({
						comments: posts.docs.map((doc) => doc.data())
					})
				)
			})
			.catch((e) => {
				// Resolve the promise in the GET route
				// with error Response (SvelteKit's Response) object
				resolve(
					new Response(e.message, {
						status: 404
					})
				)
			})
	})
}
```

---

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