diff --git a/src/routes/solid-start/advanced/auth.mdx b/src/routes/solid-start/advanced/auth.mdx new file mode 100644 index 000000000..8aa34591e --- /dev/null +++ b/src/routes/solid-start/advanced/auth.mdx @@ -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. diff --git a/src/routes/solid-start/advanced/data.json b/src/routes/solid-start/advanced/data.json index a2a44cde4..caa34d50c 100644 --- a/src/routes/solid-start/advanced/data.json +++ b/src/routes/solid-start/advanced/data.json @@ -4,6 +4,7 @@ "middleware.mdx", "session.mdx", "request-events.mdx", - "return-responses.mdx" + "return-responses.mdx", + "auth.mdx" ] }