Skip to content

Commit

Permalink
Added auth overview (#731)
Browse files Browse the repository at this point in the history
Co-authored-by: Sarah <[email protected]>
  • Loading branch information
devagrawal09 and LadyBluenotes authored May 22, 2024
1 parent f9bee27 commit 28ae1e6
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
46 changes: 46 additions & 0 deletions src/routes/solid-start/advanced/auth.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
title: "Auth"
---

Server functions can be used to protect sensitive resources like user data.

```tsx
"use server"

async function getPrivatePosts() {
const user = await getUser()
if(!user) {
return null // or throw an error
}

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

The `getUser` function can be [implemented using sessions](https://docs.solidjs.com/solid-start/advanced/session).

## Protected Routes

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");
}

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

export const route = {
load() {
void getPrivatePosts()
}
} satisfies RouteDefinition
```

Once the user hits this route, the router will immediately attempt to fetch `getPrivatePosts` data.
If the user is not signed in, `getPrivatePosts` will throw and the router will redirect to the login page.
3 changes: 2 additions & 1 deletion src/routes/solid-start/advanced/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"middleware.mdx",
"session.mdx",
"request-events.mdx",
"return-responses.mdx"
"return-responses.mdx",
"auth.mdx"
]
}

0 comments on commit 28ae1e6

Please sign in to comment.