Documentation
Configure Firebase Admin and Fireclass for an Express or Node.js application.
This guide uses @dharayush7/fireclass-js and a lazy Firebase Admin factory.
Add service-account values to a gitignored .env:
PROJECT_ID=your-project-id
CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project-id.iam.gserviceaccount.com
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n".env
serviceAccount*.jsonCreate the Firebase entry before running the CLI:
import "dotenv/config";
import { cert, getApps, initializeApp } from "firebase-admin/app";
import { getFirestore, type Firestore } from "firebase-admin/firestore";
export function getDb(): Firestore {
if (getApps().length === 0) {
initializeApp({
credential: cert({
projectId: process.env.PROJECT_ID,
clientEmail: process.env.CLIENT_EMAIL,
privateKey: process.env.PRIVATE_KEY?.replace(/\\n/g, "\n"),
}),
});
}
return getFirestore();
}Install dotenv if the application does not already load environment files,
then run the initializer:
$ npm install dotenv
$ npx fireclass init
Choose Express / Node, keep src/lib/firebase.ts, and enter getDb() as
the export. The parentheses tell Fireclass that the export is a factory.
npx fireclass doctor$ npm install @dharayush7/fireclass-js firebase-admin class-validator class-transformer reflect-metadata dotenv
For a Node ESM project, TypeScript source uses .js in relative imports:
import "reflect-metadata";
import { createFireclass } from "@dharayush7/fireclass-js";
import { getDb } from "./firebase.js";
export const { BaseModel, adapter } = createFireclass(getDb());{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}import { Collection } from "@dharayush7/fireclass-js";
import { IsBoolean, IsString } from "class-validator";
import { BaseModel } from "../lib/fireclass.js";
@Collection("todos")
export class Todo extends BaseModel<Todo> {
@IsString()
title!: string;
@IsBoolean()
done!: boolean;
constructor(data?: Partial<Todo>) {
super(data);
Object.assign(this, data);
}
}Import standalone middleware directly from the SDK:
import express from "express";
import { fireclassErrorHandler } from "@dharayush7/fireclass-js";
const app = express();
app.use(express.json());
// Register routes first.
app.use(fireclassErrorHandler());npx fireclass doctor
npm run typecheck