CloudSignal Docs
GuidesAuth Providers

Firebase integration

Configure Firebase Authentication as a provider for CloudSignal MQTT.

Configure Firebase Authentication as an auth provider so your Firebase users can connect to CloudSignal MQTT with credentials derived from their Firebase ID token. Use this when your app already authenticates users via Firebase Auth.

Prerequisites

  • A Firebase project with authentication enabled
  • A CloudSignal account with API keys
  • Firebase Admin SDK credentials (service account)

Configuration

Get Firebase project ID

  1. Go to Firebase Console
  2. Select your project
  3. Go to Project Settings (gear icon)
  4. Copy the Project ID

Add Firebase provider in CloudSignal

  1. Go to CloudSignal Dashboard
  2. Navigate to ConnectionsAuth Providers
  3. Click Add Provider
  4. Select Firebase
  5. Enter your configuration:
FieldValue
NameA friendly name (for example, "Production Firebase")
Project IDYour Firebase project ID
  1. Click Save

Test the integration

Exchange a Firebase ID token:

curl -X POST https://auth.cloudsignal.app/v2/tokens/exchange \
  -H "Authorization: Bearer YOUR_CLOUDSIGNAL_SK" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "firebase",
    "token": "YOUR_FIREBASE_ID_TOKEN"
  }'

Implementation

React/Next.js example

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import CloudSignal from '@cloudsignal/mqtt-client';

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// Connect to MQTT using the Firebase ID token
async function connectMqtt() {
  const user = auth.currentUser;

  if (!user) {
    throw new Error('User not authenticated');
  }

  // Get Firebase ID token
  const idToken = await user.getIdToken();

  const client = new CloudSignal();

  // The SDK exchanges the Firebase ID token for MQTT credentials
  await client.connectWithToken({
    host: 'wss://connect.cloudsignal.app:18885/',
    organizationId: 'org_k7xm4pqr2n5t',
    provider: 'firebase',
    externalToken: idToken,
  });

  client.setOnlineCallback(() => {
    console.log('Connected to MQTT');
  });

  return client;
}

API route (Next.js)

// app/api/mqtt-credentials/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { firebaseToken } = await request.json();

  const response = await fetch('https://auth.cloudsignal.app/v2/tokens/exchange', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.CLOUDSIGNAL_SK}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      provider: 'firebase',
      token: firebaseToken
    })
  });

  const credentials = await response.json();
  return NextResponse.json(credentials);
}

React Native / Expo example

import auth from '@react-native-firebase/auth';
import CloudSignal from '@cloudsignal/mqtt-client';

async function connectToMqtt() {
  const currentUser = auth().currentUser;

  if (!currentUser) {
    throw new Error('Not logged in');
  }

  // Get Firebase ID token
  const idToken = await currentUser.getIdToken();

  const client = new CloudSignal({ preset: 'mobile' });

  // The SDK exchanges the Firebase ID token for MQTT credentials
  await client.connectWithToken({
    host: 'wss://connect.cloudsignal.app:18885/',
    organizationId: 'org_k7xm4pqr2n5t',
    provider: 'firebase',
    externalToken: idToken,
  });

  return client;
}

Flutter example

import 'package:firebase_auth/firebase_auth.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_browser_client.dart';

class MqttService {
  MqttBrowserClient? client;

  Future<void> connect() async {
    // Get Firebase ID token
    final user = FirebaseAuth.instance.currentUser;
    if (user == null) throw Exception('Not authenticated');

    final idToken = await user.getIdToken();

    // Exchange for MQTT credentials
    final response = await http.post(
      Uri.parse('https://your-api.com/mqtt-credentials'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'firebaseToken': idToken}),
    );

    final credentials = jsonDecode(response.body);

    // Connect to MQTT
    client = MqttBrowserClient(
      'wss://connect.cloudsignal.app:18885/',
      'flutter_client'
    );

    client!.setProtocolV311();

    await client!.connect(
      credentials['mqtt_username'],
      credentials['mqtt_password']
    );
  }
}

Handling token refresh

Firebase ID tokens expire after 1 hour. Handle this gracefully:

import { getAuth, onIdTokenChanged } from 'firebase/auth';
import CloudSignal from '@cloudsignal/mqtt-client';

const auth = getAuth();
let mqttClient: CloudSignal | null = null;

// Listen for Firebase token changes and re-exchange for fresh MQTT credentials
onIdTokenChanged(auth, async (user) => {
  if (user && mqttClient) {
    // Get the refreshed Firebase ID token
    const idToken = await user.getIdToken();

    // Reconnect with the new token
    await mqttClient.disconnect();
    await mqttClient.connectWithToken({
      host: 'wss://connect.cloudsignal.app:18885/',
      organizationId: 'org_k7xm4pqr2n5t',
      provider: 'firebase',
      externalToken: idToken,
    });
  }
});

ACL rules for Firebase users

Create ACL rules that match Firebase user UIDs:

# User can only access their own topics
User Pattern: %
Topic: users/%u/#
Permission: pubsub

The MQTT username will be derived from the Firebase UID or email.

Troubleshooting

"Invalid token" error

CheckWhat to verify
Token freshnessFirebase ID tokens expire after 1 hour
Project IDMust match your Firebase project exactly
Token typeUse user.getIdToken(), not custom tokens

"Provider not found" error

CheckWhat to verify
Provider enabledConfirm the provider is enabled in CloudSignal
Provider nameUse "provider": "firebase" (lowercase)

"Token verification failed"

CheckWhat to verify
Firebase project statusEnsure Auth is enabled
Token formatShould be a valid JWT

Next steps

On this page