@dharayush7/fireclass-ssr
v2.0.9
Published
Type-safe Firestore ODM for Next.js App Router with Firebase Admin, server-only models, memoized initialization, Server Actions, and RSC serialization.
Maintainers
Keywords
Readme
@dharayush7/fireclass-ssr is the Fireclass runtime for Next.js App Router. It combines the Firebase Admin model API with memoized initialization, Server Action error handling, and a React Server Component serialization bridge.
Runtime boundaries
| Import | Environment | Purpose | | --- | --- | --- | | @dharayush7/fireclass-ssr | Server Components, Route Handlers, Server Actions | Models, Firebase Admin, actions, and serialization | | @dharayush7/fireclass-ssr/client | Client Components | Pure serialization types and date revival only |
Never import the root entry in a Client Component. It imports server-only and Firebase Admin. Use the /client entry for Serialized, serialize, serializeList, and reviveDates.
Installation
npm install @dharayush7/fireclass-ssr firebase-admin class-validator class-transformer reflect-metadata server-onlyEnable decorators in the TypeScript configuration that compiles models:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Firebase credentials
For local development, add service-account values to a gitignored .env.local:
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project-id.iam.gserviceaccount.com
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"Credential resolution order is:
- Explicit serviceAccount passed to getFireclass or initFireclassAdmin.
- FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, and FIREBASE_PRIVATE_KEY.
- Fallback aliases PROJECT_ID, CLIENT_EMAIL, and PRIVATE_KEY.
- Application Default Credentials.
Escaped \n sequences in private keys are restored automatically.
No separate Firebase file is recommended. Fireclass owns the memoized Firebase Admin initialization through getFireclass().
Create the server binding
// src/lib/fireclass.server.ts
import "reflect-metadata";
import "server-only";
import { getFireclass } from "@dharayush7/fireclass-ssr";
export const { BaseModel, adapter } = getFireclass();Only initialized values belong in this local file. Import Collection, serializeList, runAction, and other standalone helpers directly from the SDK.
Define a server-only model
// src/models/post.ts
import "server-only";
import { Collection } from "@dharayush7/fireclass-ssr";
import { IsDate, IsString, Length } from "class-validator";
import { Type } from "class-transformer";
import { BaseModel } from "../lib/fireclass.server";
@Collection("posts")
export class Post extends BaseModel<Post> {
@IsString()
@Length(1, 120)
title!: string;
@IsDate()
@Type(() => Date)
createdAt!: Date;
constructor(data?: Partial<Post>) {
super(data);
Object.assign(this, data);
}
}Read in a Server Component
// src/app/posts/page.tsx
import { serializeList } from "@dharayush7/fireclass-ssr";
import { Post } from "@/models/post";
import { PostList } from "./post-list";
export const dynamic = "force-dynamic";
export default async function PostsPage() {
const posts = await Post.findMany({
orderBy: { createdAt: "desc" },
limit: 50,
});
return <PostList initial={serializeList(posts)} />;
}Receive data in a Client Component
// src/app/posts/post-list.tsx
"use client";
import {
reviveDates,
type Serialized,
} from "@dharayush7/fireclass-ssr/client";
interface PostShape {
id?: string;
title: string;
createdAt: Date;
}
export function PostList({
initial,
}: {
initial: Serialized<PostShape>[];
}) {
return (
<ul>
{initial.map((value) => {
const post = reviveDates(value, ["createdAt"]);
return (
<li key={post.id}>
{post.title} - {post.createdAt.toLocaleDateString()}
</li>
);
})}
</ul>
);
}Mutate with a Server Action
// src/app/posts/actions.ts
"use server";
import {
runAction,
serialize,
} from "@dharayush7/fireclass-ssr";
import { revalidatePath } from "next/cache";
import { Post } from "@/models/post";
export async function createPost(formData: FormData) {
const result = await runAction(async () => {
const post = new Post({
title: String(formData.get("title") ?? ""),
createdAt: new Date(),
});
await post.save();
return serialize(post);
});
if (result.ok) {
revalidatePath("/posts");
}
return result;
}runAction returns:
type ActionResult<T> =
| { ok: true; data: T }
| { ok: false; error: string; details?: ActionFieldError[] };Validation and other Fireclass errors become serializable results. Non-Fireclass errors are re-thrown for Next.js error handling.
Export index
| Export | Purpose | | --- | --- | | getFireclass(options?) | Return the process-global BaseModel and AdminAdapter binding | | initFireclassAdmin(options?) | Initialize and cache Admin Firestore | | resetFireclassAdmin() | Clear Fireclass Admin references for isolated tests | | FireclassAdminOptions | Explicit credentials and project id | | runAction(fn) | Convert Fireclass errors into ActionResult | | serialize(model) | Convert one model to an RSC-safe plain object | | serializeList(models) | Convert a model list | | reviveDates(value, keys) | Convert selected top-level ISO strings back to Date | | Serialized | Recursive serialized model type | | Node and core exports | Models, decorators, queries, adapters, validation, and errors |
Initialization behavior
The first getFireclass() call initializes Firebase Admin and creates the adapter. Later calls return the same object; later options do not replace the cached binding.
initFireclassAdmin() reuses an existing Firebase Admin app when one exists. resetFireclassAdmin() clears Fireclass's Admin references but does not delete Firebase Admin apps or clear an already-created getFireclass() binding.
Serialization behavior
serialize copies own enumerable fields and recursively converts Date values to ISO strings. Prototype methods are excluded.
reviveDates creates a shallow copy and converts only selected top-level string fields. It does not traverse nested paths.
CLI setup
Run the CLI after credentials exist:
npx fireclass init
npx fireclass doctor
npm run buildChoose Next.js App Router. The CLI writes fireclass.json, a server-only Fireclass entry, environment templates, decorator flags, and a starter model. It uses firebase: null because this SDK owns Admin initialization.
Documentation and examples
- Next.js installation
- Complete SSR API
- Next.js App Router guide
- Core model API
- Runnable Next.js application
See CHANGELOG.md for version history and RELEASE_NOTES.md for the current release summary.
License
MIT. Copyright Ayush Dhar.
