December 21, 2022 1 min read 329 words

Using Firebase Admin with SvelteKit

Rishi Raj Jain
Rishi Raj Jain @rishi_raj_jain_

Initialize SvelteKit Starter

npm create svelte@latest my-appcd my-appnpm install

Install firebase-admin

npm install firebase-admin

Generate the firebase config

// File: src/routes/fireConfig.jsimport * 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.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 SvelteKit API Routes

// File: src/routes/api/comments/+server.jsimport admin from '../../firebase'import { json } from '@sveltejs/kit'// More on why use event driven api routes// https://kit.svelte.dev/docs/routing#server-receiving-dataexport 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                    })                )            })    })}

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