Guides / Authentication - 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 one of these examples and follow the instructions in the README:

Run the following command to install Liveblocks package:

npm install @liveblocks/node

@liveblocks/node is used from the backend to setup the 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { authorize } from "@liveblocks/node";
// Replace this key with your secret key provided at https://liveblocks.io/dashboard/apikeys
const secret = "sk_live_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 });
return res.status(result.status).end(result.body);
}

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

Auth diagram

To connect to Liveblocks, you simply 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.

1
2
3
4
5
import { createClient } from "@liveblocks/client";
// Create a liveblocks client
const client = createClient({
authEndpoint: "/api/auth",
});

Liveblocks should now be integrated with your product!

Explore our examples below to see what you can do with Liveblocks.