Guides - Authentication with Firebase

This guide assumes that you already have installed Liveblocks into your project and that you’re already familiar with Firebase functions.

Install the Liveblocks package

To do that, let’s first install @liveblocks/node package in your Firebase functions project.

npm install @liveblocks/node

Setup authentication endpoint

Next, create a new Firebase callable function as shown below. This is where you will implement your security and define if the current user has access to a specific room.

const functions = require("firebase-functions");const { authorize } = require("@liveblocks/node");
exports.auth = functions.https.onCall((data, context) => { /** * Implement your own security here. * * It's your responsibility to ensure that the caller of this endpoint * is a valid user by validating the cookies or authentication headers * and that it has access to the requested room. */ return authorize({ room: data.room, secret: "sk_prod_xxxxxxxxxxxxxxxxxxxxxxxx", userId: "123", // Optional groupIds: ["456"], // Optional userInfo: { // Optional, corresponds to the UserMeta[info] info defined in liveblocks.config.ts name: "Ada Lovelace", color: "red" }, }).then((authResult) => { if (authResult.status !== 200) { throw new functions.https.HttpsError(authResult.status, authResult.body); } return JSON.parse(authResult.body); });});

The userId used in the authorize function corresponds to userId used in our APIs when setting permissions (e.g. in create room). You can use the following example to use data from userId and userInfoon the front end.

const self = useSelf();
// "123"console.log(self.id);
// "red"console.log(self.info.color);
// ...}

Then, deploy your function with firebase deploy --only functions:auth.

Here is a diagram that shows how things work behind the scenes:

Auth diagram

Connect to Liveblocks

To connect to Liveblocks, you need to create a Liveblocks client with [createClient][] from the front-end and set the authEndpoint option based on the previously created “callable function”:

import { createClient } from "@liveblocks/client";import firebase from "firebase";import "firebase/functions";
firebase.initializeApp({ /* Firebase config */});
const auth = firebase.functions().httpsCallable("auth");
// Create a Liveblocks clientconst client = createClient({ authEndpoint: async (room) => (await auth({ room })).data,});

Liveblocks should now be integrated with your product!

© 2023 Liveblocks Inc.Edit this page