-
Notifications
You must be signed in to change notification settings - Fork 242
/
nextjs.mdx
257 lines (204 loc) · 7.39 KB
/
nextjs.mdx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
---
meta:
title: "Set up ID token permissions with Next.js"
parentTitle: "Authentication"
description: "Learn how to setup ID token permissions with Next.js."
---
Follow the following steps to start configure your authentication endpoint and
start building your own security logic in Next.js’ `/app` directory.
## Quickstart
<Steps>
<Step>
<StepTitle>Install the `liveblocks/node` package</StepTitle>
<StepContent>
```bash
npm install @liveblocks/node
```
</StepContent>
</Step>
<Step>
<StepTitle>Set up authentication endpoint</StepTitle>
<StepContent>
Users can only interact with rooms they have access to. You can
configure permission access in an `api/liveblocks-auth` endpoint by
creating the `app/api/liveblocks-auth/route.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.
```ts file="app/api/liveblocks-auth/route.ts"
import { Liveblocks } from "@liveblocks/node";
const liveblocks = new Liveblocks({
secret: "{{SECRET_KEY}}",
});
export async function POST(request: Request) {
// Get the current user from your database
const user = __getUserFromDB__(request);
// Identify the user and return the result
const { status, body } = await liveblocks.identifyUser(
{
userId: user.id,
groupIds, // Optional
},
{ userInfo: user.metadata },
);
return new Response(body, { status });
}
```
Here’s an example using the older API routes format in `/pages`.
```ts file="pages/api/liveblocks-auth.ts" isCollapsed isCollapsable
import { Liveblocks } from "@liveblocks/node";
import type { NextApiRequest, NextApiResponse } from "next";
const API_KEY = "{{SECRET_KEY}}";
const liveblocks = new Liveblocks({
secret: API_KEY!,
});
export default async function handler(request: NextApiRequest, response: NextApiResponse) {
// Get the current user from your database
const user = __getUserFromDB__(request);
// Identify the user and return the result
const { status, body } = await liveblocks.identifyUser(
{
userId: user.id,
groupIds, // Optional
},
{ userInfo: user.metadata },
);
// Authorize the user and return the result
const { status, body } = await session.authorize();
response.status(status).send(body);
}
```
</StepContent>
</Step>
<Step>
<StepTitle>Set up the client</StepTitle>
<StepContent>
On the front end, you can now replace the `publicApiKey`
option with `authEndpoint` pointing to the endpoint you
just created.
```ts file="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](/docs/api-reference/liveblocks-client#createClientCallback)
instead.
```ts file="liveblocks.config.ts" isCollapsed isCollapsable
import { createClient } from "@liveblocks/client";
// Passing custom headers and body to your endpoint
const client = createClient({
authEndpoint: async (room) => {
const headers = {
// Custom headers
// ...
"Content-Type": "application/json",
};
const body = JSON.stringify({
// Custom body
// ...
room,
});
const response = await fetch("/api/liveblocks-auth", {
method: "POST",
headers,
body,
});
return await response.json();
},
});
```
</StepContent>
</Step>
<Step>
<StepTitle>Set permission accesses to a room</StepTitle>
<StepContent>
A room can have `defaultAccesses`, `usersAccesses`, and `groupsAccesses` defined.
Permissions are then checked when users try to connect to a room. For security purposes,
[room permissions](/docs/authentication/id-token#permissions) can only be set on the back-end through `@liveblocks/node` or our REST API.
For instance, you can use [`liveblocks.createRoom`](/docs/api-reference/liveblocks-node#post-rooms)
to create a new room with read-only public access levels while giving write access to specific groups and users.
```ts highlight="7-15"
import { Liveblocks } from "@liveblocks/node";
const liveblocks = new Liveblocks({
secret: "{{SECRET_KEY}}",
});
const room = await liveblocks.createRoom("my-room-id", {
defaultAccesses: ["room:read", "room:presence:write"],
groupsAccesses: {
"my-group-id": ["room:write"],
},
usersAccesses: {
"my-user-id": ["room:write"],
},
});
```
For more information, make sure to read the section on [room permissions](/docs/authentication/id-token#permissions).
</StepContent>
</Step>
<Step lastStep>
<StepTitle>Attach metadata to users</StepTitle>
<StepContent>
Optionally, you can attach static metadata to each user, which will
be accessible in your app. First you need to define the types in
your config file, under `UserMeta["info"]`.
```ts file="liveblocks.config.ts" highlight="5-9"
type UserMeta = {
id: string;
// Example, use any JSON-compatible data in your metadata
info: {
name: string;
avatar: string;
colors: string[];
}
}
```
When authenticating, you can then pass the user’s metadata to
`prepareSession` in the endpoint we’ve just created.
```ts file="app/api/liveblocks-auth/route.ts" highlight="11-15"
// Get the current user from your database
const user = __getUserFromDB__(request);
// Identify the user and return the result
const { status, body } = await liveblocks.identifyUser(
{
userId: user.id,
groupIds, // Optional
},
{
userInfo: {
name: user.name,
avatar: user.avatarUrl,
colors: user.colorArray,
}
},
);
```
User metadata has now been set! You can access this information in your app through
[`useSelf`](/docs/api-reference/liveblocks-react#useSelf).
```tsx highlight="4"
export { useSelf } from "../liveblocks.config.ts";
function Component() {
const { name, avatar, colors } = useSelf((me) => me.info);
}
```
Bear in mind that if you’re using the [default Comments components](/docs/api-reference/liveblocks-react-comments#Components),
you must specify a `name` and `avatar` in `userInfo`.
</StepContent>
</Step>
</Steps>
## More information
Both `userId` and `userInfo` can then be used in your React application as such:
```ts
const self = useSelf();
console.log(self.id);
console.log(self.info);
```
<Figure>
<Image
src="/assets/id-token-auth-diagram.png"
alt="Auth diagram"
width={768}
height={576}
/>
</Figure>