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
import * as dotenv from 'dotenv'
dotenv.config()
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
import admin from 'firebase-admin'
import { fireConfig } from './fireConfig'
try {
admin.initializeApp({
credential: admin.credential.cert(fireConfig),
})
console.log('Initialized.')
} catch (error) {
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
import admin from '../../firebase'
import { json } from '@sveltejs/kit'
export async function GET({ request }) {
const firebase = admin.firestore()
return new Promise((resolve, reject) => {
firebase
.collection('comments')
.get()
.then((posts) => {
resolve(
json({
comments: posts.docs.map((doc) => doc.data())
})
)
})
.catch((e) => {
resolve(
new Response(e.message, {
status: 404
})
)
})
})
}