Repository navigation
Expand file tree
/
Copy pathrules.txt
More file actions
1404 lines (1171 loc) · 32.4 KB
/
Copy pathrules.txt
File metadata and controls
1404 lines (1171 loc) · 32.4 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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# What is InstantDB
Backend-as-a-Service (BaaS) with optimistic updates, multiplayer, offline support, and relational data. Firebase alternative with relations.
## Core Features
* Optimistic updates
* Real-time multiplayer sync
* Offline-first architecture
* Relational data support
* Web and mobile compatible
## API
CRITICAL: These are the only APIs from the react package you need to know. do not hallucinate other APIs.
```
// Initialization
init<Schema>(config: InstantConfig<Schema>): InstantReactWebDatabase<Schema>
// Transaction builder
tx: TxChunk<Schema>
id(): string
lookup(attribute: string, value: any): Lookup
// Schema builder
i.schema({ entities, links?, rooms? })
i.entity(attrs)
i.string(), i.number(), i.boolean(), i.date(), i.json(), i.any()
// Core Database Methods (on db instance)
db.transact(chunks)
// React Hooks (on db instance)
db.useQuery(query, opts?)
db.useAuth()
db.room(type?, id?)
// Auth Methods (on db.auth)
db.auth.sendMagicCode({ email })
db.auth.signInWithMagicCode({ email, code })
db.auth.signOut(opts?)
// Room Hooks (on db.rooms) - IMPORTANT: These are called on db.rooms, not on room instances
db.rooms.useTopicEffect(room, topic, onEvent)
db.rooms.usePublishTopic(room, topic) // returns: (data) => void
db.rooms.usePresence(room, opts?) // returns: { peers, user, publishPresence, isLoading }
db.rooms.useSyncPresence(room, data, deps?)
db.rooms.useTypingIndicator(room, inputName, opts?) // returns: { active, setActive, inputProps }
// Components
<Cursors room={room} {...props} />
```
# How to initialize DB
Create a central DB instance (single connection maintained per app ID):
```typescript
// lib/db.ts
import { init } from '@instantdb/react';
import schema from '../instant.schema';
export const db = init({
// Get your app ID from https://instantdb.com
appId: 'your-app-id',
schema
});
```
`init` accepts the following parameters:
```typescript
export type InstantConfig<S extends InstantSchemaDef<any, any, any>> = {
appId: string;
schema?: S;
};
```
# How to do queries
## Core Concepts
- **Namespaces**: Entity collections (tables)
- **Queries**: JS objects describing data needs
- **Associations**: Entity relationships
## Query Structure
```typescript
{
namespace1: {
$: { /* operators */ },
linkedNamespace: { $: { /* operators */ } }
},
namespace2: { /* ... */ }
}
```
## Basic Usage
**Required**: Handle `isLoading` and `error` states:
```typescript
const { isLoading, data, error } = db.useQuery({ todos: {} })
if (isLoading) return
if (error) return (<div>Error: {error.message}</div>)
return <pre>{JSON.stringify(data, null, 2)}</pre>
```
### Fetch Operations
```typescript
// Single namespace
const query = { goals: {} }
// Multiple namespaces
const query = { goals: {}, todos: {} }
```
## Filtering
### By ID
```typescript
const query = {
goals: {
$: { where: { id: 'goal-1' } }
}
}
```
### Multiple Conditions (AND)
```typescript
const query = {
todos: {
$: { where: { completed: true, priority: 'high' } }
}
}
```
## Associations (JOINs)
### Fetch Related
```typescript
// Goals with todos
const query = { goals: { todos: {} } }
// Inverse: Todos with goals
const query = { todos: { goals: {} } }
```
### Filter by Association
```typescript
// Dot notation for associated values
const query = {
goals: {
$: { where: { 'todos.title': 'Go running' } },
todos: {}
}
}
```
### Filter Associated Entities
```typescript
const query = {
goals: {
todos: {
$: { where: { completed: true } }
}
}
}
```
## Operators
### Logical
```typescript
// AND
where: { and: [{ 'todos.priority': 'high' }, { 'todos.dueDate': { $lt: tomorrow } }] }
// OR
where: { or: [{ priority: 'high' }, { dueDate: { $lt: tomorrow } }] }
```
### Comparison (indexed fields only)
- `$gt`, `$lt`, `$gte`, `$lte`
```typescript
where: { timeEstimate: { $gt: 2 } }
```
### Other Operators
```typescript
// IN
where: { priority: { $in: ['high', 'critical'] } }
// NOT
where: { location: { $not: 'work' } }
// NULL check
where: { location: { $isNull: true } }
// Pattern matching (indexed strings)
where: { title: { $like: 'Get%' } } // Case-sensitive
where: { title: { $ilike: 'get%' } } // Case-insensitive
```
Pattern syntax:
- `'prefix%'` - Starts with
- `'%suffix'` - Ends with
- `'%substring%'` - Contains
## Pagination & Ordering
### Pagination (top-level only)
```typescript
$: { limit: 10, offset: 10 }
```
### Ordering (indexed fields)
```typescript
$: { order: { dueDate: 'asc' } } // or 'desc'
```
## Field Selection
```typescript
// Select specific fields
$: { fields: ['title', 'status'] }
// With nested associations
goals: {
$: { fields: ['title'] },
todos: { $: { fields: ['status'] } }
}
```
## Deferred Queries
```typescript
const query = user ? { todos: { $: { where: { userId: user.id } } } } : null
```
## Complex Example
```typescript
const query = {
goals: {
$: {
where: { or: [{ status: 'active' }, { 'todos.priority': 'high' }] },
limit: 5,
order: { serverCreatedAt: 'desc' },
fields: ['title', 'description']
},
todos: {
$: {
where: { completed: false, dueDate: { $lt: nextWeek } },
fields: ['title', 'dueDate']
}
}
}
}
```
## Best Practices
1. Index fields for filtering/sorting/comparison
2. Use field selection to minimize data transfer
3. Defer queries when dependencies aren't ready
4. Limit deep association nesting
5. Use where/limit/pagination for large datasets
## Common Errors
- **"Field must be indexed"**: Add index in Explorer/schema
- **"Invalid operator"**: Check syntax/spelling
- **"Invalid query structure"**: Verify $ placement
# How to do transactions
## Core Concepts
- **Transactions**: Atomic operation groups
- **Transaction Chunks**: Individual operations
- **Proxy Syntax**: `db.tx` object for creating chunks
## Basic Structure
```typescript
db.transact(db.tx.NAMESPACE[ENTITY_ID].ACTION(DATA))
```
## Entity IDs
### Generate with `id()`
```typescript
import { id } from '@instantdb/react'
// New ID
const newTodoId = id()
db.transact(db.tx.todos[newTodoId].update({ text: "New todo" }))
// Inline
db.transact(db.tx.todos[id()].update({ text: "Another todo" }))
```
### Lookup by Unique Attributes
```typescript
import { lookup } from '@instantdb/react'
// Schema must define unique attributes
db.transact(
db.tx.profiles[lookup('handle', 'nezaj')].update({
bio: 'I like turtles'
})
)
```
## Creating Entities
Use `update` (not `create`):
```typescript
db.transact(db.tx.todos[id()].update({
text: "Complex todo", // String
priority: 1, // Number
completed: false, // Boolean
tags: ["work", "important"], // Array
metadata: { // Object
assignee: "user-123",
dueDate: "2025-01-15"
}
}))
```
## Updating Entities
### Basic Update
```typescript
db.transact(db.tx.todos[todoId].update({ done: true }))
```
### Deep Merge (nested objects)
```typescript
// Preserves unspecified nested fields
db.transact(db.tx.profiles[userId].merge({
preferences: { theme: "dark" }
}))
```
### Remove Keys
```typescript
db.transact(db.tx.profiles[userId].merge({
preferences: { notifications: null }
}))
```
## Deleting Entities
```typescript
// Single
db.transact(db.tx.todos[todoId].delete())
// Multiple
db.transact([
db.tx.todos[todoId1].delete(),
db.tx.todos[todoId2].delete()
])
// Conditional
const completedTodos = data.todos.filter(todo => todo.done)
db.transact(completedTodos.map(todo => db.tx.todos[todo.id].delete()))
```
## Relationships
### Link Entities
```typescript
// Single link
db.transact(db.tx.projects[projectId].link({ todos: todoId }))
// Multiple links
db.transact(db.tx.projects[projectId].link({
todos: [todoId1, todoId2, todoId3]
}))
// Bidirectional (equivalent)
db.transact(db.tx.projects[projectId].link({ todos: todoId }))
db.transact(db.tx.todos[todoId].link({ projects: projectId }))
```
### Unlink
```typescript
db.transact(db.tx.projects[projectId].unlink({ todos: todoId }))
```
### Link with Lookup
```typescript
db.transact(
db.tx.profiles[lookup('email', 'user@example.com')].link({
projects: lookup('name', 'Project Alpha')
})
)
```
## Advanced Operations
### Combined Operations
```typescript
// Update + link
db.transact(
db.tx.todos[id()]
.update({ text: "New todo", done: false })
.link({ projects: projectId })
)
// Multiple in transaction
db.transact([
db.tx.todos[todoId].update({ done: true }),
db.tx.projects[projectId].update({ completedCount: 10 })
])
```
### Special Namespaces
```typescript
// Link to authenticated user ($users is system namespace)
db.transact(db.tx.todos[todoId].link({ $users: auth.userId }))
```
## Performance
### Batch Large Operations
```typescript
const batchSize = 100
const createManyTodos = async (count) => {
for (let i = 0; i < count; i += batchSize) {
const batch = []
for (let j = 0; j < batchSize && i + j < count; j++) {
batch.push(
db.tx.todos[id()].update({
text: `Todo ${i + j}`,
done: false
})
)
}
await db.transact(batch)
}
}
```
## Common Patterns
### Create-or-Update
```typescript
db.transact(
db.tx.profiles[lookup('email', 'user@example.com')].update({
lastLoginAt: Date.now()
})
)
```
### Toggle Boolean
```typescript
const toggleTodo = (todo) => {
db.transact(db.tx.todos[todo.id].update({ done: !todo.done }))
}
```
### Sequential Transactions
```typescript
const createProjectAndTasks = async (projectData) => {
const result = await db.transact(
db.tx.projects[id()].update(projectData)
)
const projectId = result.ids.projects[0]
await db.transact(
db.tx.tasks[id()].update({
title: "Initial planning"
}).link({ project: projectId })
)
}
```
## Error Handling
```typescript
try {
await db.transact(/* ... */)
} catch (error) {
console.error("Transaction failed:", error)
}
```
## Important: Make sure to use `transact` inside a `useEffect` or event handler
Do not use `transact` inside a component render. This will cause an error.
```typescript
// ❌ Wrong
function MyComponent() {
// This will cause an error
db.transact(db.tx.todos[id()].update({ text: "New todo" }))
return <div>My component</div>
}
// ✅ Correct
function MyComponent() {
const handleClick = () => {
db.transact(db.tx.todos[id()].update({ text: "New todo" }))
}
return <button onClick={handleClick}>Create todo</button>
}
```
## Common Mistakes
- Using non-UUID IDs (must use `id()` or `lookup()`)
- Using `create` method (doesn't exist, use `update`)
- Direct `$users` updates (link only)
- Using `update` for nested objects (use `merge`)
- Not batching large transactions
- Using `lookup` on non-unique fields
- Using `transact` in render (use `useEffect` or event handlers)
# How to model data
Schema is declared as code. System namespaces start with `$` (e.g., `$users`).
## Core Concepts
- **Namespaces**: Entity collections (tables)
- **Attributes**: Entity properties with types
- **Links**: Entity relationships
- **Rooms**: Ephemeral namespaces (cursors, etc.)
## Schema Setup
```typescript
// instant.schema.ts
import { i } from '@instantdb/react';
const _schema = i.schema({
entities: { /* namespaces */ },
links: { /* relationships */ },
rooms: { /* ephemeral data */ }
});
type _AppSchema = typeof _schema;
interface AppSchema extends _AppSchema {}
const schema: AppSchema = _schema;
export type { AppSchema };
export default schema;
```
## Namespaces
```typescript
entities: {
profiles: i.entity({ /* attributes */ }),
posts: i.entity({ /* attributes */ }),
comments: i.entity({ /* attributes */ })
}
```
Rules:
- Alphanumeric + underscores
- No spaces
- Unique names
- No `$` prefix (reserved)
## Attributes
### Types
| Type | Description | Example |
|------|-------------|---------|
| `i.string()` | Text | `title: i.string()` |
| `i.number()` | Numeric | `viewCount: i.number()` |
| `i.boolean()` | True/false | `isPublished: i.boolean()` |
| `i.date()` | Date/time | `publishedAt: i.date()` |
| `i.json()` | Nested objects | `metadata: i.json()` |
| `i.any()` | Untyped | `miscData: i.any()` |
### Constraints & Performance
```typescript
posts: i.entity({
slug: i.string().unique(), // Unique + auto-indexed
title: i.string(),
category: i.string().indexed(), // Indexed for queries
publishedAt: i.date().indexed()
})
```
## Links (Relationships)
### Basic Structure
```typescript
links: {
postAuthor: {
forward: { on: 'posts', has: 'one', label: 'author' },
reverse: { on: 'profiles', has: 'many', label: 'authoredPosts' }
}
}
```
### Relationship Types
**One-to-One**
```typescript
profileUser: {
forward: { on: 'profiles', has: 'one', label: '$user' },
reverse: { on: '$users', has: 'one', label: 'profile' }
}
```
**One-to-Many**
```typescript
postAuthor: {
forward: { on: 'posts', has: 'one', label: 'author' },
reverse: { on: 'profiles', has: 'many', label: 'authoredPosts' }
}
```
**Many-to-Many**
```typescript
postsTags: {
forward: { on: 'posts', has: 'many', label: 'tags' },
reverse: { on: 'tags', has: 'many', label: 'posts' }
}
```
### System Namespace Links
Always link TO system namespaces in reverse:
```typescript
// ✅ Correct
forward: { on: 'profiles', has: 'one', label: '$user' },
reverse: { on: '$users', has: 'one', label: 'profile' }
```
### Cascade Delete
```typescript
postAuthor: {
forward: { on: 'posts', has: 'one', label: 'author', onDelete: 'cascade' },
reverse: { on: 'profiles', has: 'many', label: 'authoredPosts' }
}
```
## Complete Example
```typescript
import { i } from '@instantdb/react';
const _schema = i.schema({
entities: {
$users: i.entity({
email: i.string().unique().indexed()
}),
profiles: i.entity({
nickname: i.string().unique(),
bio: i.string(),
createdAt: i.date().indexed()
}),
posts: i.entity({
title: i.string(),
slug: i.string().unique().indexed(),
body: i.string(),
isPublished: i.boolean().indexed(),
publishedAt: i.date().indexed()
}),
comments: i.entity({
body: i.string(),
createdAt: i.date().indexed()
}),
tags: i.entity({
name: i.string().unique().indexed()
})
},
links: {
profileUser: {
forward: { on: 'profiles', has: 'one', label: '$user', onDelete: 'cascade' },
reverse: { on: '$users', has: 'one', label: 'profile', onDelete: 'cascade' }
},
postAuthor: {
forward: { on: 'posts', has: 'one', label: 'author', onDelete: 'cascade' },
reverse: { on: 'profiles', has: 'many', label: 'authoredPosts' }
},
commentPost: {
forward: { on: 'comments', has: 'one', label: 'post', onDelete: 'cascade' },
reverse: { on: 'posts', has: 'many', label: 'comments' }
},
commentAuthor: {
forward: { on: 'comments', has: 'one', label: 'author', onDelete: 'cascade' },
reverse: { on: 'profiles', has: 'many', label: 'authoredComments' }
},
postsTags: {
forward: { on: 'posts', has: 'many', label: 'tags' },
reverse: { on: 'tags', has: 'many', label: 'posts' }
}
}
});
type _AppSchema = typeof _schema;
interface AppSchema extends _AppSchema {}
const schema: AppSchema = _schema;
export type { AppSchema };
export default schema;
```
## TypeScript Integration
```typescript
import { InstaQLEntity } from '@instantdb/react';
import { AppSchema } from '../instant.schema';
// Type-safe entities
type Post = InstaQLEntity<AppSchema, 'posts'>;
type PostWithAuthor = InstaQLEntity<AppSchema, 'posts', { author: {} }>;
function PostEditor({ post }: { post: Post }) {
return <h1>{post.title}</h1>;
}
```
## Important: Do not use the same label for an attribute and a reference
If you do this this will cause errors when you try to query the data. Make sure
to use different labels for attributes and references.
```typescript
const _schema = i.schema({
entities: {
notes: i.entity({
title: i.string().indexed(),
content: i.string(),
// ❌ Wrong: `tags` is both an attribute and a reference
tags: i.json(),
isPinned: i.boolean().indexed(),
createdAt: i.date().indexed(),
updatedAt: i.date().indexed()
}),
tags: i.entity({
name: i.string().unique().indexed(),
color: i.string()
})
},
links: {
notesTags: {
forward: { on: 'notes', has: 'many', label: 'tags' },
reverse: { on: 'tags', has: 'many', label: 'notes' }
}
}
});
```
## Best Practices
1. Index frequently queried attributes
2. Use unique constraints for usernames, slugs
3. Clear, descriptive link labels
4. Set cascade delete for dependent relationships
5. Use TypeScript utility types
## Common Mistakes
- Creating `$` prefixed namespaces
- Not indexing query fields
- Ambigious attribute and reference labels
- Wrong system namespace link direction
- Using non-indexed fields in queries/sorting
# How to write permissions
Define access controls using Google's CEL expression language.
## Core Operations
- **view**: Read access (queries)
- **create**: Create new entities
- **update**: Modify existing entities
- **delete**: Remove entities
## Default Behavior
All permissions default to `true` (unrestricted).
```typescript
// These are equivalent:
{} // Empty rules
{ todos: { allow: {} } } // No rules specified
{ todos: { allow: { view: "true", create: "true", update: "true", delete: "true" } } }
```
## Key Features
### `$default` for Namespace Defaults
```typescript
{
todos: {
allow: {
$default: "false", // Deny all by default
view: "auth.id != null" // Explicitly allow viewing
}
}
}
```
### `auth` and `data` Objects
- `auth`: Current authenticated user
- `data`: Current entity being accessed
```typescript
{
todos: {
allow: {
view: "auth.id != null",
update: "auth.id == data.ownerId"
}
}
}
```
### `bind` for Reusable Logic
```typescript
{
todos: {
allow: {
view: "isLoggedIn",
$default: "isOwner || isAdmin"
},
bind: [
"isLoggedIn", "auth.id != null",
"isOwner", "isLoggedIn && auth.id == data.ownerId",
"isAdmin", "isLoggedIn && auth.email in ['admin@example.com']"
]
}
}
```
### `data.ref` for Linked Data
Returns CEL list - use `in` operator or index `[0]` for single values.
```typescript
// ✅ Correct
"update": "auth.id in data.ref('post.author.id')"
"view": "auth.id == data.ref('owner.id')[0]"
"view": "size(data.ref('owner.id')) > 0"
// ❌ Wrong
"update": "auth.id == data.ref('post.author.id')" // Always returns list
"view": "data.ref('owner')" // Must specify attribute
"view": "data.ref('owner.id') != null" // Check against [] not null
```
### `auth.ref` for User's Linked Data
Must use `$user` prefix.
```typescript
// ✅ Correct
"create": "'admin' in auth.ref('$user.role.type')"
"create": "auth.ref('$user.role.type')[0] == 'admin'"
// ❌ Wrong
"create": "'admin' in auth.ref('role.type')" // Missing $user prefix
```
### `newData` for Update Comparisons
```typescript
{
posts: {
allow: {
// Authors can update but not change published status
update: "auth.id == data.authorId && newData.isPublished == data.isPublished"
}
}
}
```
### `ruleParams` for Non-Auth Permissions
```typescript
// app/page.tsx
const docId = new URLSearchParams(window.location.search).get("docId");
const { data } = db.useQuery({ docs: {} }, { ruleParams: { docId } });
db.transact(
db.tx.docs[docId].ruleParams({ docId }).update({ title: 'eat' })
);
// instant.perms.ts
{
documents: {
allow: {
view: "data.id == ruleParams.docId",
update: "data.id == ruleParams.docId"
}
}
}
```
## Complete Examples
### Blog Platform
```typescript
// instant.perms.ts
{
posts: {
allow: {
view: "data.isPublished || isAuthor",
create: "auth.id != null && isAuthor",
update: "isAuthor || isAdmin",
delete: "isAuthor || isAdmin"
},
bind: [
"isAuthor", "auth.id == data.authorId",
"isAdmin", "auth.ref('$user.role')[0] == 'admin'"
]
},
comments: {
allow: {
view: "true",
create: "isCommentAuthor",
update: "isCommentAuthor",
delete: "isCommentAuthor || isPostAuthor || isAdmin"
},
bind: [
"isLoggedIn", "auth.id != null",
"isPostAuthor", "isLoggedIn && auth.id == data.ref('post.authorId')[0]",
"isCommentAuthor", "isLoggedIn && auth.id == data.authorId",
"isAdmin", "auth.ref('$user.role')[0] == 'admin'"
]
}
}
```
### Todo App
```typescript
// instant.perms.ts
{
todos: {
allow: {
view: "isOwner || isShared",
create: "isOwner",
update: "isOwner || (isShared && data.ownerId == newData.ownerId)",
delete: "isOwner"
},
bind: [
"isLoggedIn", "auth.id != null",
"isOwner", "isLoggedIn && auth.id == data.ownerId",
"isShared", "isLoggedIn && auth.id in data.ref('sharedWith.id')"
]
},
lists: {
allow: {
$default: "isOwner",
view: "isOwner || isCollaborator"
},
bind: [
"isLoggedIn", "auth.id != null",
"isOwner", "isLoggedIn && auth.id == data.ownerId",
"isCollaborator", "isLoggedIn && auth.id in data.ref('collaborators.id')"
]
}
}
```
## Common Mistakes
- Not using `data.ref` for linked data
- Missing attribute in `data.ref('owner')` → `data.ref('owner.id')`
- Using `==` with lists instead of `in` operator
- Missing `$user` prefix with `auth.ref`
- Checking `data.ref` against `null` instead of `[]`
- Using `newData.ref` (doesn't exist)
- Non-literal strings in ref: `data.ref(var + '.id')` → `data.ref('team.id')`
# How to get the current user
You can get the current user by using the `useAuth` hook.
```typescript
const { isLoading, user, error } = db.useAuth();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (user) return <AuthenticatedApp user={user} />;
return <UnauthenticatedApp />;
```
# How to implenent authentication
Instant supports magic code authentication. There is no built-in username/password authentication.
## Core concepts
1. User enters email
2. InstantDB sends verification code
3. User enters code
4. Authentication complete
## Complete Example
```typescript
// instant.schema.ts
import { i } from '@instantdb/react';
const _schema = i.schema({
entities: {
$users: i.entity({
email: i.string().unique().indexed(),
}),
},
});
type _AppSchema = typeof _schema;
interface AppSchema extends _AppSchema {}
const schema: AppSchema = _schema;
export type { AppSchema };
export default schema;
// lib/db.ts