Guides - Authentication with Next.js

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

Alternatively, you can copy this example and follow the instructions in the README:

Install the Liveblocks package

Run the following command to install Liveblocks package:

npm install @liveblocks/node

@liveblocks/node is used from the backend to setup the authentication endpoint.

Setup authentication endpoint

Users can only interact with rooms they have access to. You can configure permission access in an api/auth endpoint by creating the pages/api/auth.js 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.

import { authorize } from "@liveblocks/node";
// Replace this key with your secret key provided at// https://liveblocks.io/dashboard/projects/{projectId}/apikeysconst secret = "sk_prod_xxxxxxxxxxxxxxxxxxxxxxxx";
export default async function auth(req, res) { /** * 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. */ const room = req.body.room; const result = await authorize({ room, secret, userId: "123", // Optional groupIds: ["456"], // Optional userInfo: { // Optional name: "Ada Lovelace", }, }); return res.status(result.status).end(result.body);}

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 path of the endpoint created earlier.

import { createClient } from "@liveblocks/client";
// Create a Liveblocks clientconst client = createClient({ authEndpoint: "/api/auth",});

Liveblocks should now be integrated with your product!

© 2022 Liveblocks Inc.Edit this page