LaunchFast Logo Introducing LaunchFa.st - Astro boilerplate
Wednesday, December 21 2022

Using Firebase Admin with SvelteKit

Rishi Raj Jain
Rishi Raj Jain @rishi_raj_jain_

Initialize SvelteKit Starter

npm create svelte@latest my-app
cd my-app
npm install

Install firebase-admin

npm install firebase-admin

Generate the firebase config

// 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

// 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

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

Write a comment

Email will remain confidential.