-
Notifications
You must be signed in to change notification settings - Fork 438
Expand file tree
/
Copy pathnextjs-starter-kit.mdx
More file actions
653 lines (527 loc) · 20.9 KB
/
Copy pathnextjs-starter-kit.mdx
File metadata and controls
653 lines (527 loc) · 20.9 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
---
meta:
title: "Next.js Starter Kit"
parentTitle: "Tools"
description:
"Kickstart your collaborative SaaS product with the Liveblocks Next.js
Starter Kit."
---
The Next.js Starter Kit is an open-source template that showcases all aspects of
Liveblocks in a single, modern application.
<Figure>
<video height={1080} width={1592} autoPlay loop muted playsInline>
<source src="/assets/nextjs-starter-kit/starter-kit.mp4" type="video/mp4" />
</video>
</Figure>
<Banner title="Live demo">
If you’d like to see how this works, make sure to
[check out this live demo video](https://www.youtube.com/watch?v=Lf7HQ4Z_Ovc) on
YouTube, or [try the project online](https://nextjs-starter-kit.liveblocks.app).
</Banner>
## Features
The Next.js Starter Kit includes the following
- Documents dashboard with pagination, organizations, auto-revalidation.
- Collaborative apps including a whiteboard, text documents, note editor,
drawing canvas.
- Realtime presence with avatars, cursors, carets.
- Fully-featured share menu with users, organizations, public permissions.
- Authentication compatible with GitHub, Google, Auth0, and more.
<Figure>
<video height={1080} width={1592} autoPlay loop muted playsInline>
<source
src="/assets/nextjs-starter-kit/starter-kit-apps.mp4"
type="video/mp4"
/>
</video>
</Figure>
## Set up the Next.js Starter Kit
### create-liveblocks-app
You can get started by running the following command:
```bash
npx create-liveblocks-app@latest --next
```
This will run an installer that allows you to download, configure, and deploy,
your project:
<Figure>
<video autoPlay loop muted playsInline>
<source
src="/assets/nextjs-starter-kit/create-liveblocks-app.mp4"
type="video/mp4"
/>
</video>
</Figure>
Give your project a name, and select the [authentication](#authentication)
method you’d like to use in your app. If you are trying to generate a proof of
concept quickly, opting to use demo authentication may be a great option—you can
still add other authentication providers later on.
#### Deploy with Vercel Integration
If you would like to set up CI/CD with your application, we’ve made that process
straightforward for you as well. When prompted, you can select "deploy to
Vercel" to enable building and deploying the starter kit. The Vercel Integration
will open in a new browser window for you to complete the process of adding your
repository.
<Figure>
<video autoPlay loop muted playsInline>
<source
src="/assets/nextjs-starter-kit/deploy-on-vercel.mp4"
type="video/mp4"
/>
</video>
</Figure>
If by clicking "Create" you receive "An unexpected internal error occurred" you
should validate within your code hosting platform of choice (GitHub, GitLab,
Bitbucket) that the Vercel integration has permission to access your repository.
In GitHub, permissions can be found can be found under Settings > Integrations >
Vercel.
#### Connect to Liveblocks and retrieve your secret key
If you prefer to work locally, you can tell the installer you would not like to
"deploy to Vercel". After declining the deployment option, the installer will
prompt adding your Liveblocks Key to the application automatically. If you
forwent deployment or indicated that you would like to get your Liveblocks
secret key automatically, the Liveblocks integration page will open in a new
browser tab. Once the integration page appears, you can sign up/sign in to
Liveblocks, create a new project, and import your API key into the installer.
<Figure>
<video autoPlay loop muted playsInline>
<source
src="/assets/nextjs-starter-kit/create-liveblocks-project.mp4"
type="video/mp4"
/>
</video>
</Figure>
After finishing up, check the installer and follow the commands recommended to
get you started.
### Authentication [#authentication]
The Liveblocks starter kit uses [NextAuth.js](https://next-auth.js.org/) for
authentication, meaning many authentication providers can be configured with
minimal code changes. A demo authentication system is used by default, but it’s
easy to add real providers, such as GitHub, Auth0, and more.
Take a look at the guide for your chosen authentication method:
- [GitHub authentication](#github-authentication)
- [Auth0 authentication](#auth0-authentication)
- [Demo authentication](#demo-authentication)
### GitHub authentication [#github-authentication]
To use GitHub auth, make sure you selected "GitHub authentication" when running
the installer (or you’ve set up the
[provider manually](#add-multiple-authentication-providers)). This is how to set
up your GitHub secret key and client id.
1. Go to [Developer Settings](https://github.com/settings/apps) on GitHub and
click "New GitHub App".
2. Enter an app name (e.g. `Liveblocks Starter Kit (dev)`). You’ll need a new
app for each environment, so it’s helpful to place "dev" in the name.
3. Add a homepage URL—this isn’t important now, so a placeholder will do.
4. Find the "Callback URL" input just below, and add your local development URL
(e.g. `http://localhost:3000`).
5. Look for the "Webhook" section and make sure to uncheck "Active".
6. Use the remaining default settings and press "Create GitHub App".
<Figure>
<video autoPlay loop muted playsInline>
<source src="/assets/nextjs-starter-kit/github-auth.mp4" type="video/mp4" />
</video>
</Figure>
7. On the next page under "Client secrets", press the "Generate a new client
secret" button (note that this is different to generating a private key!).
8. Copy this secret into the `/.env.local` file as `GITHUB_CLIENT_SECRET`
9. Go back to the previous page and find the "Client ID" near the top. Copy this
into your `.env.local` file as `GITHUB_CLIENT_ID`
Almost there! `.env.local` should now contain lines similar to this:
```env file=".env.local"
GITHUB_CLIENT_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GITHUB_CLIENT_ID=XXXXXXXXXXXXXXXXXXXX
```
GitHub authentication is now complete! Next,
[add yourself as a user](#how-to-sign-up) to test out your authentication.
### Auth0 authentication [#auth0-authentication]
To use Auth0 auth, make sure you selected "Auth0 authentication" when running
the installer (or you’ve set up the
[provider manually](#add-multiple-authentication-providers)). This is how to set
up your Auth0 secret key and client information.
1. Go to your [Auth0 Dashboard](https://manage.auth0.com/dashboard) and click
"Create Application".
2. Enter an app name (e.g. `Liveblocks Starter Kit (dev)`). You’ll need a new
app for each environment, so it’s helpful to place "dev" in the name.
3. Select "Single Page Web Applications", and press "Create".
4. Copy your "Client ID" from the top of the page, and place it within
`.env.local` as `AUTH0_CLIENT_ID`.
5. Click the "Settings" tab— we’ll be making a number of changes here.
6. Find the "Client Secret" input field, and copy the value into `.env.local` as
`AUTH0_CLIENT_SECRET`.
7. Copy your "Domain" from the input field, add "https://" to the start, and
place it within `.env.local` as `AUTH0_ISSUER_BASE_URL`.
8. Add the following to the "Allowed Callback URLs" textarea:
`http://localhost:3000/api/auth/callback/auth0`.
9. Add the following to the "Allowed Logout URLs" textarea:
`http://localhost:3000`.
10. Scroll to the bottom and press "Save changes".
<Figure>
<video autoPlay loop muted playsInline>
<source src="/assets/nextjs-starter-kit/auth0-auth.mp4" type="video/mp4" />
</video>
</Figure>
`.env.local` should now contain these three lines, along with anything
previously there:
```env file=".env.local"
AUTH0_CLIENT_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
AUTH0_CLIENT_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
AUTH0_ISSUER_BASE_URL=https://XXXXXXXXXXXXXXXXXX.com
```
Auth0 authentication is now set up! Next, [add yourself a user](#how-to-sign-up)
to test out your authentication.
### Demo authentication [#demo-authentication]
For quickly testing out your app, the demo authentication method can be used.
This method uses a NextAuth
[`CredentialsProvider`](https://next-auth.js.org/providers/credentials) to
simulate a real sign in system. To replace it with your own authentication
method, you can add any other NextAuth
[`Provider`](https://next-auth.js.org/providers/) to
[`/auth.config.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/auth.config.ts).
Read the [next section](#how-to-sign-up) to learn how to add a new user to your
demo application.
### How to sign up - add yourself as a user [#how-to-sign-up]
We haven’t set up a database, so we’re temporarily using the
[`/data`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/data)
folder instead. Before any user can sign in, they need to be added to
[`/data/users.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/data/users.ts).
Navigate there and add your details, for example, if you’re signing in with
`yourname@example.com`:
```ts file="data/users.ts"
{
id: "your.name@example.com",
name: "Your Name",
avatar: "https://liveblocks.io/avatars/avatar-0.png",
organizationIds: ["liveblocks", "your.name@example.com"],
},
```
Note that this is replacing the sign-up process, so you must enter the email of
any new user. If, for example, you’re using GitHub authentication, you can enter
the email address of any valid GitHub account.
### Ready to go
The Next.js Starter Kit is now ready to use! After setting up authentication,
make sure to restart the dev server to see your authentication in action.
```bash
npm run dev
```
## Assorted info
### Structure
The
[starter kit](https://github.com/liveblocks/liveblocks/tree/main/starter-kits/nextjs-starter-kit)
has the following structure:
```
app
components
data
icons
layouts
lib
└─ actions
└─ database
└─ hooks
└─ utils
primitives
styles
types
utils
auth.ts
auth.config.ts
constants.ts
liveblocks.config.ts
liveblocks.server.config.ts
package.json
```
The important thing to note is that there are primitives, which are base level
components such as buttons (think of these as the small building blocks of a
page), components, which you can think of as multiplayer implementations
(cursors, badges, etc), app, which renders document level experiences and a
library (lib) of both server side and client side methods which contain the
logic to create and modify documents.
<br />
<details>
<summary>More info about the structure</summary>
<br />
<dl>
<dt>`/app/`</dt>
<dd>Next.js app folder.</dd>
<dt>`/components/`</dt>
<dd>Components used in the app.</dd>
<dt>`/data/`</dt>
<dd>A demo database.</dd>
<dt>`/icons/`</dt>
<dd>Every icon component.</dd>
<dt>`/layouts/`</dt>
<dd>Page layout components.</dd>
<dt>`/lib/actions/`</dt>
<dd>
Server actions that can be used on both client and server, used for
accessing and modifying documents.
</dd>
<dt>`/lib/database/`</dt>
<dd>Server functions used for getting database information.</dd>
<dt>`/lib/hooks/`</dt>
<dd>A set of React hooks that are used on the client.</dd>
<dt>`/lib/utils/`</dt>
<dd>Assorted document-related utilities.</dd>
<dt>`/primitives/`</dt>
<dd>Generic reusable components.</dd>
<dt>`/types/`</dt>
<dd>All reusable TypeScript types.</dd>
<dt>`/auth.ts`</dt>
<dd>File that links NextAuth to your database.</dd>
<dt>`/auth.config.ts`</dt>
<dt>File where NextAuth providers are set up.</dt>
<dt>`/constants.ts`</dt>
<dd>Constant strings used in the app, such as URLs and global IDs.</dd>
<dt>`/liveblocks.config.ts`</dt>
<dd>Liveblocks config file.</dd>
<dt>`/liveblocks.server.config.ts`</dt>
<dd>Server-side Liveblocks config file.</dd>
</dl>
</details>
### Async fetching and error handling
This starter kit makes extensive use of the following programming pattern for
fetching async resources:
```ts
const { data, error } = await getDocument({
/* ... */
});
// An error has occurred
if (error) {
// { code: 400, message: "Document not found", suggestion: "Please check the URL is..." }
console.log(error);
return;
}
// Success, but result is empty
if (!data) {
return;
}
// Success
// { name: "my-document", id: "hIas7GuihgHF8Fhv8Sskg", ... }
console.log(data);
```
### Document functions
Much of the starter kit’s power is in the
[`/lib/actions`](https://github.com/liveblocks/liveblocks/tree/main/starter-kits/nextjs-starter-kit/lib/actions)
directory. The functions in these files allow you to edit your documents easily
and return type-safe objects. For example in an API endpoint:
```ts
import { createDocument } from "@/lib/actions";
export async function POST() {
// Create a new document
const { data, error } = await createDocument({
name: "My document",
type: "whiteboard",
userId: "charlie.layne@example.com",
});
// ...
}
```
Because these functions are server actions, they can be leveraged on both client
and server.
```tsx
import { createDocument } from "@/lib/actions";
export function CreateDocumentButton() {
async function handleCreateDocument() {
// Create a new document
const { data, error } = await createDocument({
name: "My document",
type: "whiteboard",
userId: "charlie.layne@example.com",
});
}
return <button onClick={handleCreateDocument}>New document</button>;
}
```
Functions that return data can be used with [SWR hooks](https://swr.vercel.app/)
that automatically update your data in components. For example,
`getDocumentUsers` returns a list of users with access to the room:
```tsx
// Convert from this
const { data, error } = await getDocumentUsers({
documentId: "my-document-id",
});
// To this
const { data, error } = useDocumentsFunctionSWR([
getDocumentUsers,
{
documentId: "my-document-id",
},
]);
```
Here’s a working example:
```tsx
import { getDocumentUsers, useDocumentsFunctionSWR } from "../../lib/client";
export function ListUsers() {
// Get users attached to a document and update every 1000ms
const { data: users, error: usersError } = useDocumentsFunctionSWR(
[
getDocumentUsers,
{
documentId: "my-document-id",
},
],
{ refreshInterval: 1000 }
);
if (usersError) {
return <div>Error</div>;
}
if (!users) {
return <div>Loading...</div>;
}
return (
<ul>
{users.map((user) => (
<li>user.name</li>
))}
</ul>
);
}
```
### How to extend the Document type
If you’d like to add a new property to `Document`, it’s simple. First, edit the
`Document` type in
[`/types/documents.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/types/document.ts):
```ts file="types/documents.ts"
export type Document = {
// Your new property
randomNumber: number;
//...
};
```
Then modify the return value in
[`/lib/utils/buildDocuments.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/utils/buildDocuments.ts).
This is a function that converts a Liveblocks room into your custom document
format:
```ts file="lib/utils/buildDocuments.ts"
// Return our custom Document format
const document: Document = {
randomNumber: Math.random(),
// ...
};
```
Next, run the following command to check for problems:
```bash
npm run typecheck
```
If no errors are returned, the document properties were successfully extended.
### How to extend the User & Session type
Similar to the way we extend the `Document` type, we can also extend the `User`
and `Session` type.
Adding a new property to `User`/`Session` is simple. First, edit the `User` type
in
[`/types/data.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/types/data.ts).
```ts file="types/data.ts"
export type User = {
// Your new property
randomNumber: number;
// ...
};
```
Then make sure to return this new property in
[`/lib/database/getUser.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/database/getUser.ts).
```ts file="lib/database/getUser.ts"
return { randomNumber: Math.random() /* ... */ };
```
The new property will now be available to use in your app:
```ts
// randomNumber: Math.random(),
console.log(session.user.info.randomNumber);
```
#### Adding this to your Liveblocks app (optional)
Liveblocks presence is a way of displaying online presence between users,
helpful for live avatars, realtime cursors, etc., and it’s possible to attach a
properties to it for each user. To make a property accessible in presence (and
within the React hooks used in whiteboard), you must modify `UserInfo` in
[`/liveblocks.config.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/liveblocks.config.ts).
```ts file="liveblocks.config.ts"
export type UserInfo = Pick<User, "randomNumber" /* ... */>;
```
In this example
[Pick](https://www.typescriptlang.org/docs/handbook/utility-types.html) creates
the UserInfo type based off of the User type and adds additional keys based on
the properties you provide. After this, modify
[`/lib/actions/authorizeLiveblocks.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/actions/authorizeLiveblocks.ts).
First, we’ll give an anonymous user a property:
```ts file="lib/actions/authorizeLiveblocks.ts"
// Anonymous user info
const anonymousUser: User = {
randomNumber: Math.random(),
// ...
};
```
Next, we’ll get the signed-in user’s property:
```ts file="lib/actions/authorizeLiveblocks.ts"
// Get current user info from session (defined in /auth.config.ts)
// If no session found, this is a logged out/anonymous user
const {
randomNumber,
// ...
} = session?.user.info ?? anonymousUser;
```
And then pass this info to `authorize`:
```ts file="lib/actions/authorizeLiveblocks.ts"
// Get Liveblocks access token
const { data, error } = await authorize({
userInfo: { randomNumber /* ... */ },
// ...
});
```
To make sure to check everything’s hooked up correctly:
```bash
npm run typecheck
```
Once that’s working, the new property can then be used in your app:
```tsx
// My random number
const myRandomNumber = useSelf((me) => me.info.randomNumber);
// An array of everyone else’s random numbers
const everyonesRandomNumbers = useOthersMapped(
(other) => other.info.randomNumber
);
```
### Adding multiple authentication providers [#add-multiple-authentication-providers]
It’s possible to add multiple authentication providers to the starter kit using
[NextAuth Providers](https://next-auth.js.org/providers/). Open
[`/auth.config.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/auth.config.ts)
and place your providers in the object:
```ts
import GithubProvider from "next-auth/providers/github";
import Auth0Provider from "next-auth/providers/auth0";
export const authOptions = {
// ...
providers: {
GithubProvider({
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
}),
Auth0Provider({
clientId: process.env.AUTH0_CLIENT_ID as string,
clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
issuer: process.env.AUTH0_ISSUER_BASE_URL as string,
}),
}
};
```
It’s not only possible with GitHub and Auth0, any
[NextAuth provider](https://next-auth.js.org/providers/) will work, such as
Google, X, Reddit, or more. You can find more information about getting the
necessary secrets on the NextAuth documentation, or on the provider’s website.
Note that if you’re using `CredentialsProvider` (for example, as used in the
demo authentication), `CredentialsProvider` must be removed before any other
authentication methods will appear.
### Switching themes
The starter kit comes with both a dark mode and light mode. By default, the user
sees the theme that corresponds to their system setting, but it’s easy to switch
your whole app to just dark or light mode by modifying
[`styles/globals.css`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/styles/globals.css).
- To use only light mode, remove the entire
`@media (prefers-color-scheme: dark)` media query.
- To use only dark mode, copy the "Dark mode" CSS variables into the "Light
mode" section, then remove the entire `@media (prefers-color-scheme: dark)`
media query.
### Adding a database
To add a database you need to modify the following async functions to return the
correct properties:
- [`/lib/database/getGroup.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/database/getGroup.ts)
- [`/lib/database/getGroups.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/database/getGroups.ts)
- [`/lib/database/getOrganization.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/database/getOrganization.ts)
- [`/lib/database/getUser.ts`](https://github.com/liveblocks/liveblocks/blob/main/starter-kits/nextjs-starter-kit/lib/database/getUser.ts)
You can then remove the `/data` folder. Everything else should work as expected.