From 877edc47405af6841251015a1eba3868b4355afa Mon Sep 17 00:00:00 2001 From: ulic75 Date: Sat, 3 Jun 2023 17:07:43 -0600 Subject: [PATCH] docs: add qwik-auth route protection example (#4119) --- .../src/routes/docs/integrations/authjs/index.mdx | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/docs/src/routes/docs/integrations/authjs/index.mdx b/packages/docs/src/routes/docs/integrations/authjs/index.mdx index 12db73ea9ee..e057909f7d1 100644 --- a/packages/docs/src/routes/docs/integrations/authjs/index.mdx +++ b/packages/docs/src/routes/docs/integrations/authjs/index.mdx @@ -230,3 +230,18 @@ AUTH_SECRET= 4. The application is now ready to impliment authentication using Auth.js. 5. Enjoy! + +### Route Protection + +Session data can be accessed via the route `event.sharedMap`. So a route can be protected and redirect using something like this located in a `layout.tsx` or page `index.tsx`: + +```tsx +export const onRequest: RequestHandler = (event) => { + const session: Session | null = event.sharedMap.get('session'); + if (!session || new Date(session.expires) < new Date()) { + throw event.redirect(302, `/api/auth/signin?callbackUrl=${event.url.href}`); + } +}; +``` + +> Note: If placed in a layout.tsx ensure that the redirect destination does not share the same layout.tsx or a redirection loop could occur. \ No newline at end of file