Authentication - Set up access token permissions with SvelteKit

Follow the following steps to start configure your authentication endpoint and start building your own security logic.

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 src/routes/api/liveblocks-auth/+server.ts file with the following code. This is where you will implement your security and define the rooms that the user has access to.

    The client will request a token either for a specific room, in which case the request body property room will be defined, or for resources outside a specific room (like notifications), in which case, room will be undefined.

    See permissions with access token to understand how to grant access to multiple rooms with an access token.

    src/routes/api/liveblocks-auth/+server.ts
    import { type RequestEvent } from "@sveltejs/kit";import { Liveblocks } from "@liveblocks/node";
    const liveblocks = new Liveblocks({ secret: "",});
    export async function POST({ request }: RequestEvent) { // Get the current user from your database const user = (request);
    // 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/organization. // Note: Even if room is defined, we recommend to always use wildcards. const { room } = request.body; if (room && (user, room)) { session.allow(room, session.FULL_ACCESS); } else { session.allow(`${user.organization}*`, session.READ_ACCESS) }
    // Authorize the user and return the result const { status, body } = await session.authorize(); return new Response(body, { status });}
  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 Svelte application as such:

const self = room.getSelf();console.log(self.id);console.log(self.info.color);
Auth diagram