LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Overview
  • Prerequisites
  • Installation
  • Initializing Firebase
  • 1. Create a Firebase Configuration File
  • 2. Initialize Firebase in a Service
  • Using Firebase Authentication in Components
  • Firestore Real-Time Updates

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Recipes

Firebase integration

Overview

Integrate Firebase into your Aurelia 2 application to enable real-time data, authentication, and cloud storage. This recipe walks you through setting up Firebase, handling authentication, and performing basic Firestore operations using Firebase's modern modular SDK.

Prerequisites

  • An existing Aurelia 2 project.

  • A Firebase project with configuration details (API key, project ID, etc.).

  • Node.js and npm installed.

Installation

Install the latest Firebase SDK:

npm install firebase

Initializing Firebase

1. Create a Firebase Configuration File

Create src/firebase-config.ts and add your configuration:

// src/firebase-config.ts
export const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
  appId: 'YOUR_APP_ID'
};

2. Initialize Firebase in a Service

Create a Firebase service using the modular SDK:

// src/services/firebase-service.ts
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword, signOut } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { firebaseConfig } from '../firebase-config';

class FirebaseService {
  app = initializeApp(firebaseConfig);
  auth = getAuth(this.app);
  db = getFirestore(this.app);

  async login(email: string, password: string) {
    return signInWithEmailAndPassword(this.auth, email, password);
  }

  async logout() {
    return signOut(this.auth);
  }
}

export const firebaseService = new FirebaseService();

Using Firebase Authentication in Components

Inject and use the Firebase service in your components:

// src/components/login.ts
import { customElement } from 'aurelia';
import { firebaseService } from '../services/firebase-service';

@customElement({
  name: 'login',
  template: `<button click.trigger="login()">Login</button>
             <button click.trigger="logout()">Logout</button>`
})
export class Login {
  async login() {
    try {
      const userCredential = await firebaseService.login('user@example.com', 'password');
      console.log('Logged in:', userCredential.user);
    } catch (error) {
      console.error('Login error:', error);
    }
  }

  async logout() {
    await firebaseService.logout();
    console.log('Logged out');
  }
}

Firestore Real-Time Updates

Use Firestore to listen for real-time updates:

// src/components/todo-list.ts
import { customElement } from 'aurelia';
import { firebaseService } from '../services/firebase-service';
import { collection, onSnapshot } from 'firebase/firestore';

@customElement({
  name: 'todo-list',
  template: `
    <ul>
      <li repeat.for="todo of todos">${todo.text}</li>
    </ul>
  `
})
export class TodoList {
  todos: any[] = [];

  constructor() {
    const todosCollection = collection(firebaseService.db, 'todos');
    onSnapshot(todosCollection, (snapshot) => {
      this.todos = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    });
  }
}
PreviousDOM style injectionNextMarkdown integration

Last updated 2 months ago

Was this helpful?