Getting Started

Learn how to install and configure FireBlazor in your Blazor WebAssembly application.

Installation

Install FireBlazor via NuGet Package Manager or the .NET CLI:

# Using .NET CLI
dotnet add package FireBlazor
Requirements

FireBlazor requires:

  • .NET 8.0, 9.0, or 10.0
  • Blazor WebAssembly project
  • A Firebase project with desired services enabled

Configuration

Configure FireBlazor in your Program.cs file. Here's a complete example with all available options:

// 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")));

Configuration Options

Method Description
WithProject() Your Firebase project ID
WithApiKey() Your Firebase Web API key
WithAuthDomain() Authentication domain for OAuth flows
WithStorageBucket() Cloud Storage bucket URL
WithDatabaseUrl() Realtime Database URL
UseAuth() Enable authentication with providers
UseFirestore() Enable Cloud Firestore
UseStorage() Enable Cloud Storage
UseRealtimeDatabase() Enable Realtime Database
UseAppCheck() Enable App Check with reCAPTCHA

Initialize Firebase

Before using any Firebase services, you need to initialize the SDK. Do this in your main layout or app component:

@inject IFirebase Firebase

@code {
    protected override async Task OnInitializedAsync()
    {
        await Firebase.InitializeAsync();
    }
}
Important

Always call InitializeAsync() before attempting to use any Firebase services. This ensures the JavaScript SDK is properly loaded and configured.

Basic Usage

Once initialized, you can access Firebase services through the IFirebase interface. Here's an example showing how to subscribe to authentication state changes:

@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);
        };
    }
}

This pattern allows your components to react to authentication changes in real-time, automatically updating the UI when users sign in or out.

Blazor Authorization

FireBlazor integrates seamlessly with Blazor's built-in authorization system. Enable it by adding AddFirebaseAuthorization to your services:

// Program.cs
builder.Services.AddFirebaseAuthorization(options =>
{
    options.LoginPath = "/login";
    options.AccessDeniedPath = "/access-denied";
});

Once configured, you can use standard Blazor authorization features:

// Use [Authorize] attribute on pages
@page "/dashboard"
@attribute [Authorize]

<h1>Dashboard</h1>

// Or use AuthorizeView component
<AuthorizeView>
    <Authorized>
        <p>Hello, @context.User.Identity?.Name!</p>
    </Authorized>
    <NotAuthorized>
        <p>Please sign in to continue.</p>
    </NotAuthorized>
</AuthorizeView>
Tip

The LoginPath is where unauthenticated users are redirected. The AccessDeniedPath is where authenticated users without proper permissions are redirected.

Emulator Support

FireBlazor provides full support for the Firebase Emulator Suite, making local development and testing a breeze:

builder.Services.AddFirebase(options => options
    .WithProject("demo-project")
    // ... other configuration
    .UseEmulators(emulators => emulators
        .Auth("localhost:9099")
        .Firestore("localhost:8080")
        .Storage("localhost:9199")
        .RealtimeDatabase("localhost:9000")));

You can also configure all emulators at once with default ports:

// Configure all emulators with default ports
.UseEmulators(emulators => emulators.All("localhost"))

Default Emulator Ports

Service Default Port
Authentication 9099
Cloud Firestore 8080
Cloud Storage 9199
Realtime Database 9000

Testing

FireBlazor provides fake implementations for unit testing, allowing you to test your components without connecting to Firebase:

// Register fake services in your test setup
services.AddSingleton<IFirebase, FakeFirebase>();

// In your tests
var fakeFirebase = serviceProvider
    .GetRequiredService<IFirebase>() as FakeFirebase;

// Configure fake authentication state
fakeFirebase.FakeAuth.SetCurrentUser(new FirebaseUser
{
    Uid = "test-user",
    Email = "test@example.com",
    DisplayName = "Test User"
});

// Reset between tests
fakeFirebase.Reset();
Testing Best Practice

Always call Reset() between tests to ensure a clean state. The fake implementations maintain state across calls, just like the real Firebase services.

Configuration from appsettings.json

For production applications, you may want to store your Firebase configuration in appsettings.json:

{
  "Firebase": {
    "ProjectId": "your-project-id",
    "ApiKey": "your-api-key",
    "AuthDomain": "your-project.firebaseapp.com",
    "StorageBucket": "your-project.firebasestorage.app",
    "DatabaseUrl": "https://your-project.firebasedatabase.app"
  }
}

Then load the configuration in Program.cs:

builder.Services.AddFirebase(configuration, options => options
    .UseAuth()
    .UseFirestore());
Security Note

Firebase Web API keys are safe to expose in client-side code - they only identify your project. Security is enforced through Firebase Security Rules. Never expose service account credentials or admin SDK keys in client-side applications.