Skip to content

Commit

Permalink
Use route component in Protected Routes example (solidjs#769)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brendonovich authored Jun 11, 2024
1 parent c19e385 commit 5062586
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/routes/solid-start/advanced/auth.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async function getPrivatePosts() {
if(!user) {
return null // or throw an error
}

return db.getPosts({ userId: user.id, private: true })
}
```
Expand All @@ -21,26 +21,24 @@ The `getUser` function can be [implemented using sessions](/solid-start/advanced

## Protected Routes

Routes can be protected by checking the user or session object during data fetching.
Routes can be protected by checking the user or session object during data fetching.
This example uses [Solid Router](/solid-router).

```tsx
const getPrivatePosts = cache(async function() {
"use server"
const user = await getUser()
if(!user) {
throw redirect("/login");
throw redirect("/login");
}

return db.getPosts({ userId: user.id, private: true })
})

export const route = {
load() {
void getPrivatePosts()
}
} satisfies RouteDefinition
export default function Page() {
const posts = createAsync(() => getPrivatePosts());
}
```

Once the user hits this route, the router will immediately attempt to fetch `getPrivatePosts` data.
Once the user hits this route, the router will attempt to fetch `getPrivatePosts` data.
If the user is not signed in, `getPrivatePosts` will throw and the router will redirect to the login page.

0 comments on commit 5062586

Please sign in to comment.