File tree 2 files changed +48
-1
lines changed
src/routes/solid-start/advanced 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : " Auth"
3
+ ---
4
+
5
+ Server functions can be used to protect sensitive resources like user data.
6
+
7
+ ``` tsx
8
+ " use server"
9
+
10
+ async function getPrivatePosts() {
11
+ const user = await getUser ()
12
+ if (! user ) {
13
+ return null // or throw an error
14
+ }
15
+
16
+ return db .getPosts ({ userId: user .id , private: true })
17
+ }
18
+ ```
19
+
20
+ The ` getUser ` function can be [ implemented using sessions] ( https://docs.solidjs.com/solid-start/advanced/session ) .
21
+
22
+ ## Protected Routes
23
+
24
+ Routes can be protected by checking the user or session object during data fetching.
25
+ This example uses [ Solid Router] ( /solid-router ) .
26
+
27
+ ``` tsx
28
+ const getPrivatePosts = cache (async function () {
29
+ " use server"
30
+ const user = await getUser ()
31
+ if (! user ) {
32
+ throw redirect (" /login" );
33
+ }
34
+
35
+ return db .getPosts ({ userId: user .id , private: true })
36
+ })
37
+
38
+ export const route = {
39
+ load() {
40
+ void getPrivatePosts ()
41
+ }
42
+ } satisfies RouteDefinition
43
+ ```
44
+
45
+ Once the user hits this route, the router will immediately attempt to fetch ` getPrivatePosts ` data.
46
+ If the user is not signed in, ` getPrivatePosts ` will throw and the router will redirect to the login page.
Original file line number Diff line number Diff line change 4
4
" middleware.mdx" ,
5
5
" session.mdx" ,
6
6
" request-events.mdx" ,
7
- " return-responses.mdx"
7
+ " return-responses.mdx" ,
8
+ " auth.mdx"
8
9
]
9
10
}
You can’t perform that action at this time.
0 commit comments