Skip to content

Commit 28ae1e6

Browse files
Added auth overview (#731)
Co-authored-by: Sarah <gerrardsarah@gmail.com>
1 parent f9bee27 commit 28ae1e6

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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.

src/routes/solid-start/advanced/data.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"middleware.mdx",
55
"session.mdx",
66
"request-events.mdx",
7-
"return-responses.mdx"
7+
"return-responses.mdx",
8+
"auth.mdx"
89
]
910
}

0 commit comments

Comments
 (0)