Authentication - Set up access token permissions with Express

Follow the following steps to start configure your authentication endpoint where

Quickstart

  1. Install the liveblocks/node package

    $npm install @liveblocks/node
  2. Set up authentication endpoint

    Users can only interact with rooms they have access to. You can configure permission access in an api/liveblocks-auth endpoint by creating the liveblocks-auth.ts file with the following code. This is where you will implement your security and define if the current user has access to a specific room.

    liveblocks-auth.ts
    const express = require("express");import { Liveblocks } from "@liveblocks/node";
    const liveblocks = new Liveblocks({ secret: "sk_prod_xxxxxxxxxxxxxxxxxxxxxxxx",});
    const app = express();app.use(express.json());
    app.post("/api/liveblocks-auth", (req, res) => { // Get the current user from your database const user = __getUserFromDB__(req);
    // Start an auth session inside your endpoint const session = liveblocks.prepareSession( user.id, { userInfo: user.metadata }, // Optional );
    // Implement your own security, and give the user access to the room if (req.body.room && __shouldUserHaveAccess__(user, req.body.room)) { session.allow(req.body.room, session.FULL_ACCESS); }
    // Authorize the user and return the result const { status, body } = await session.authorize(); return res.status(status).end(body);});
  3. Set up the client

    On the front end, you can now replace the publicApiKey option with authEndpoint pointing to the endpoint you just created.

    liveblocks.config.ts
    import { createClient } from "@liveblocks/client";
    const client = createClient({ authEndpoint: "/api/liveblocks-auth",});

    If you need to pass custom headers or data to your endpoint, you can use authEndpoint as a callback instead.

More information

Both userId and userInfo can then be used in your JavaScript application as such:

const self = room.getSelf(); // or useSelf() in Reactconsole.log(self.id);console.log(self.info);
Auth diagram