UNPKG

denwa-react-shared

Version:
101 lines (81 loc) 2.78 kB
--- name: session-auth description: > Manage authentication sessions, parse server responses, and validate identity cookies using Zod schemas. Use for handling login flow results and session integrity checks. type: core library: denwa-react-shared library_version: "1.0.88" sources: - "Denwa799/react-shared:src/shared/schemas/index.ts" --- # Session & Auth Management This skill covers the standardization of server responses and session state validation using Zod schemas. All API interactions should be validated against these schemas to ensure data consistency. ## Setup ```typescript import { responseSchema, sessionCookieSchema } from 'denwa-react-shared'; // Example: Validating an API response const handleApiResponse = (data: unknown) => { const result = responseSchema.safeParse(data); if (!result.success) { console.error('API format mismatch:', result.error); return; } return result.data; }; ``` ## Core Patterns ### Parsing Session Cookies Use `sessionCookieSchema` to validate the structure of the authentication cookie before using it in the application. ```typescript import { sessionCookieSchema } from 'denwa-react-shared'; const validateSession = (cookieData: unknown) => { const session = sessionCookieSchema.parse(cookieData); return { isLoggedIn: !!session.tokens.accessToken.token, userRoles: session.roles, isAdmin: session.roles.includes('admin'), }; }; ``` ### Handling Standard Error Envelopes The `responseSchema` includes a structured `error` field. Always check for both the top-level `error` object and `statusCode`. ```typescript import { responseSchema } from 'denwa-react-shared'; async function fetchData(url: string) { const response = await fetch(url); const data = await response.json(); const parsed = responseSchema.parse(data); if (parsed.error) { throw new Error(parsed.error.message || 'Unknown error'); } return parsed.data; } ``` ## Common Mistakes ### MEDIUM Manually parsing cookies without schema Wrong: ```typescript const id = JSON.parse(cookies.get('session')).id; ``` Correct: ```typescript const session = sessionCookieSchema.parse(cookies.get('session')); const id = session.id; ``` Manually accessing properties bypasses validation and creates runtime risks if the session structure changes. Source: maintainer interview ### HIGH Ignoring the data/response duality Wrong: ```typescript // Expecting data to always be the result const users = response.data; ``` Correct: ```typescript // Checking both data and any legacy response fields const users = response.data ?? response.response; ``` The `responseSchema` allows for flexibility in return fields (`data` vs `response`). Agents should account for both. Source: src/shared/schemas/index.ts