FireBlazor
Firebase SDK for Blazor WebAssembly - Zero boilerplate, delightful DX. Auth, Firestore, Storage, Realtime Database, App Check & AI Logic.
Install / Use
/learn @mashrulhaque/FireBlazorREADME
FireBlazor
Firebase for Blazor - Zero boilerplate, delightful DX
A comprehensive, type-safe Firebase SDK for Blazor WebAssembly applications. FireBlazor provides first-class .NET integration with Firebase services including Authentication, Cloud Firestore, Cloud Storage, Realtime Database, App Check, and Firebase AI Logic (Gemini).
Documentation | Getting Started | API Reference
Why FireBlazor?
Looking for a Firebase SDK for Blazor or a .NET Firebase alternative? The official Firebase JavaScript SDK doesn't integrate well with Blazor's component model. FireBlazor solves this with:
| FireBlazor | JS SDK via Interop |
|------------|-------------------|
| Native C# types | Manual JS interop |
| LINQ-style queries | String-based queries |
| Result<T> error handling | Try-catch exceptions |
| Blazor authorization integration | Manual auth state |
| IntelliSense & compile-time safety | Runtime errors |
| Full emulator support | Complex setup |
Perfect for: Blazor WebAssembly apps needing Firebase Authentication, Firestore, Storage, Realtime Database, or Gemini AI.
Demo
<!-- TODO: Add screenshot or GIF of sample app --> <!--  -->Check out the sample application to see FireBlazor in action.
Features
- Firebase Authentication - Email/password, Google, GitHub, Microsoft OAuth
- Cloud Firestore - LINQ-style queries, real-time subscriptions, transactions, batch operations
- Cloud Storage - File upload/download with progress tracking, metadata management
- Realtime Database - Real-time synchronization, presence detection, offline support
- App Check - reCAPTCHA v3/Enterprise integration for backend protection
- Firebase AI Logic - Gemini model integration with streaming, function calling, and grounding
- Result Pattern - Functional error handling without exceptions
- Blazor Authorization - Seamless integration with
[Authorize]and<AuthorizeView> - Emulator Support - Full local development with Firebase Emulator Suite
- Testing Infrastructure - Complete fake implementations for unit testing
Installation
dotnet add package FireBlazor
Getting Started
1. Configure Services
// Program.cs
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddFirebase(options => options
.WithProject("your-project-id")
.WithApiKey("your-api-key")
.WithAuthDomain("your-project.firebaseapp.com")
.WithStorageBucket("your-project.firebasestorage.app")
.WithDatabaseUrl("https://your-project.firebasedatabase.app")
.UseAuth(auth => auth
.EnableEmailPassword()
.EnableGoogle("google-client-id"))
.UseFirestore()
.UseStorage()
.UseRealtimeDatabase()
.UseAppCheck(appCheck => appCheck
.ReCaptchaV3("your-recaptcha-site-key")));
// Optional: Enable Blazor authorization
builder.Services.AddFirebaseAuthorization(options =>
{
options.LoginPath = "/login";
options.AccessDeniedPath = "/access-denied";
});
2. Initialize Firebase
@inject IFirebase Firebase
@code {
protected override async Task OnInitializedAsync()
{
await Firebase.InitializeAsync();
}
}
3. Use Firebase Services
@inject IFirebase Firebase
<h3>Welcome, @_user?.DisplayName</h3>
@code {
private FirebaseUser? _user;
protected override void OnInitialized()
{
_user = Firebase.Auth.CurrentUser;
Firebase.Auth.OnAuthStateChanged += user =>
{
_user = user;
InvokeAsync(StateHasChanged);
};
}
}
Authentication
FireBlazor supports multiple authentication providers:
// Email/Password
var result = await Firebase.Auth.SignInWithEmailAsync("user@example.com", "password");
var result = await Firebase.Auth.CreateUserWithEmailAsync("user@example.com", "password");
// OAuth Providers
var result = await Firebase.Auth.SignInWithGoogleAsync();
var result = await Firebase.Auth.SignInWithGitHubAsync();
var result = await Firebase.Auth.SignInWithMicrosoftAsync();
// Sign Out
await Firebase.Auth.SignOutAsync();
// Get ID Token
var tokenResult = await Firebase.Auth.GetIdTokenAsync(forceRefresh: true);
User Properties
FirebaseUser user = Firebase.Auth.CurrentUser;
// user.Uid, user.Email, user.DisplayName, user.PhotoUrl
// user.IsEmailVerified, user.IsAnonymous, user.Providers
// user.CreatedAt, user.LastSignInAt
Cloud Firestore
CRUD Operations
// Create
var result = await Firebase.Firestore
.Collection<TodoItem>("todos")
.AddAsync(new TodoItem { Title = "Buy groceries", Completed = false });
// Read
var result = await Firebase.Firestore
.Collection<TodoItem>("todos")
.Where(t => t.Completed == false)
.OrderBy(t => t.CreatedAt)
.Take(10)
.GetAsync();
// Update
var result = await Firebase.Firestore
.Collection<TodoItem>("todos")
.Document("doc-id")
.UpdateAsync(new { Completed = true });
// Delete
var result = await Firebase.Firestore
.Collection<TodoItem>("todos")
.Document("doc-id")
.DeleteAsync();
Real-time Subscriptions
var unsubscribe = Firebase.Firestore
.Collection<TodoItem>("todos")
.Where(t => t.UserId == currentUserId)
.OnSnapshot(
snapshot => {
_items = snapshot.ToList();
InvokeAsync(StateHasChanged);
},
error => Console.WriteLine(error.Message));
// Later: unsubscribe();
Transactions & Batch Operations
// Transaction
var result = await Firebase.Firestore.TransactionAsync<string>(async tx =>
{
var fromDoc = Firebase.Firestore.Collection<Account>("accounts").Document("from");
var toDoc = Firebase.Firestore.Collection<Account>("accounts").Document("to");
var fromSnap = await tx.GetAsync(fromDoc);
var toSnap = await tx.GetAsync(toDoc);
tx.Update(fromDoc, new { Balance = fromSnap.Value.Data.Balance - 100 });
tx.Update(toDoc, new { Balance = toSnap.Value.Data.Balance + 100 });
return "Transfer complete";
});
// Batch
var result = await Firebase.Firestore.BatchAsync(batch =>
{
batch.Set(collection.Document("doc1"), item1);
batch.Update(collection.Document("doc2"), new { Status = "updated" });
batch.Delete(collection.Document("doc3"));
});
Field Values
// Server timestamp
await docRef.UpdateAsync(new { UpdatedAt = FieldValue.ServerTimestamp() });
// Atomic increment
await docRef.UpdateAsync(new { ViewCount = FieldValue.Increment(1) });
// Array operations
await docRef.UpdateAsync(new { Tags = FieldValue.ArrayUnion("new-tag") });
await docRef.UpdateAsync(new { Tags = FieldValue.ArrayRemove("old-tag") });
Aggregate Queries
var count = await Firebase.Firestore.Collection<Item>("items").Aggregate().CountAsync();
var total = await Firebase.Firestore.Collection<Order>("orders").Aggregate().SumAsync("amount");
var avg = await Firebase.Firestore.Collection<Product>("products").Aggregate().AverageAsync("price");
Cloud Storage
Upload Files
// Upload with progress
var result = await Firebase.Storage
.Ref($"uploads/{Guid.NewGuid()}/{file.Name}")
.PutAsync(
browserFile,
new StorageMetadata { ContentType = file.ContentType },
progress => {
_uploadProgress = progress.Percentage;
InvokeAsync(StateHasChanged);
});
// Upload string content
await Firebase.Storage
.Ref("data/config.json")
.PutStringAsync(jsonContent, StringFormat.Raw, new StorageMetadata { ContentType = "application/json" });
Download Files
// Get download URL
var urlResult = await Firebase.Storage.Ref("path/to/file.png").GetDownloadUrlAsync();
// Download as bytes
var bytesResult = await Firebase.Storage.Ref("path/to/file.png").GetBytesAsync(maxSize: 10_000_000);
// Download as stream
var streamResult = await Firebase.Storage.Ref("path/to/file.png").GetStreamAsync();
Manage Files
// Get metadata
var metadata = await Firebase.Storage.Ref("path/to/file").GetMetadataAsync();
// Update metadata
await Firebase.Storage.Ref("path/to/file").UpdateMetadataAsync(new StorageMetadata
{
CacheControl = "public, max-age=3600",
CustomMetadata = new Dictionary<string, string> { ["version"] = "1.0" }
});
// Delete
await Firebase.Storage.Ref("path/to/file").DeleteAsync();
// List files
var listResult = await Firebase.Storage.Ref("uploads").ListAllAsync();
Realtime Database
Basic Operations
// Set data
await Firebase.RealtimeDb.Ref("users/user1").SetAsync(userData);
// Push data (auto-generated key)
var pushResult = await Firebase.RealtimeDb.Ref("messages").PushAsync(message);
// Get data
var result = await Firebase.RealtimeDb.Ref("users/user1").GetAsync<User>();
// Update data
await Firebase.RealtimeDb.Ref("users/user1").UpdateAsync(new { Status = "online" });
// Remove data
await Firebase.RealtimeDb.Ref("users/user1").RemoveAsync();
Real-time Listeners
var unsubscribe = Firebase.RealtimeDb
.Ref("messages")
.OrderByChild("timestamp"
