[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EP093SNR69N67M0VYY49J6":3,"skill-same:01M6EP093SNR69N67M0VYY49J6":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6EP093SNR69N67M0VYY49J6","web-auth",null,"Authentication patterns for React web applications. Use when implementing login flows, OAuth, JWT handling, session management, or protected routes in React web apps.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Fcjharmath\u002Fweb-auth\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"web","auth","web auth","react","authentication","OAuth","jwt","applications","management","session","use","patterns","apps","authentication patterns","react web","session management","2026-11-10 10:12:30",false,"---\nname: web-auth\ndescription: Authentication patterns for React web applications. Use when implementing login flows, OAuth, JWT handling, session management, or protected routes in React web apps.\n---\n\n# Web Authentication (React)\n\n## Core Patterns\n\n### JWT Token Storage\n\n**Options and trade-offs:**\n\n| Storage | XSS Safe | CSRF Safe | Best For |\n|---------|----------|-----------|----------|\n| httpOnly cookie | Yes | No (needs CSRF token) | Most secure for tokens |\n| localStorage | No | Yes | Simple apps, short-lived tokens |\n| Memory (state) | Yes | Yes | Very short-lived tokens with refresh |\n\n### Cookie-Based Auth (Recommended)\n\n```typescript\n\u002F\u002F API client setup\nconst api = {\n  async login(email: string, password: string) {\n    const response = await fetch('\u002Fapi\u002Fauth\u002Flogin', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      credentials: 'include', \u002F\u002F Important: send\u002Freceive cookies\n      body: JSON.stringify({ email, password }),\n    });\n    return response.json();\n  },\n\n  async logout() {\n    await fetch('\u002Fapi\u002Fauth\u002Flogout', {\n      method: 'POST',\n      credentials: 'include',\n    });\n  },\n\n  async getUser() {\n    const response = await fetch('\u002Fapi\u002Fauth\u002Fme', {\n      credentials: 'include',\n    });\n    if (!response.ok) throw new Error('Not authenticated');\n    return response.json();\n  },\n};\n```\n\n### Auth Context Pattern\n\n```typescript\nimport { createContext, useContext, useEffect, useState, ReactNode } from 'react';\n\ninterface User {\n  id: string;\n  email: string;\n  name: string;\n}\n\ninterface AuthState {\n  user: User | null;\n  isLoading: boolean;\n  isAuthenticated: boolean;\n  login: (email: string, password: string) => Promise\u003Cvoid>;\n  logout: () => Promise\u003Cvoid>;\n  refresh: () => Promise\u003Cvoid>;\n}\n\nconst AuthContext = createContext\u003CAuthState | null>(null);\n\nexport function AuthProvider({ children }: { children: ReactNode }) {\n  const [user, setUser] = useState\u003CUser | null>(null);\n  const [isLoading, setIsLoading] = useState(true);\n\n  useEffect(() => {\n    \u002F\u002F Check auth status on mount\n    checkAuth();\n  }, []);\n\n  async function checkAuth() {\n    try {\n      const userData = await api.getUser();\n      setUser(userData);\n    } catch {\n      setUser(null);\n    } finally {\n      setIsLoading(false);\n    }\n  }\n\n  async function login(email: string, password: string) {\n    const { user } = await api.login(email, password);\n    setUser(user);\n  }\n\n  async function logout() {\n    await api.logout();\n    setUser(null);\n  }\n\n  async function refresh() {\n    await checkAuth();\n  }\n\n  return (\n    \u003CAuthContext.Provider\n      value={{\n        user,\n        isLoading,\n        isAuthenticated: !!user,\n        login,\n        logout,\n        refresh,\n      }}\n    >\n      {children}\n    \u003C\u002FAuthContext.Provider>\n  );\n}\n\nexport function useAuth() {\n  const context = useContext(AuthContext);\n  if (!context) {\n    throw new Error('useAuth must be used within AuthProvider');\n  }\n  return context;\n}\n```\n\n---\n\n## OAuth Patterns\n\n### Google OAuth (Web)\n\n```typescript\n\u002F\u002F Using Google Identity Services\nimport { useEffect } from 'react';\n\ndeclare global {\n  interface Window {\n    google: any;\n  }\n}\n\nfunction GoogleLoginButton() {\n  useEffect(() => {\n    \u002F\u002F Load Google Identity Services script\n    const script = document.createElement('script');\n    script.src = 'https:\u002F\u002Faccounts.google.com\u002Fgsi\u002Fclient';\n    script.async = true;\n    document.body.appendChild(script);\n\n    script.onload = () => {\n      window.google.accounts.id.initialize({\n        client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,\n        callback: handleGoogleResponse,\n      });\n\n      window.google.accounts.id.renderButton(\n        document.getElementById('google-signin'),\n        { theme: 'outline', size: 'large' }\n      );\n    };\n\n    return () => {\n      document.body.removeChild(script);\n    };\n  }, []);\n\n  async function handleGoogleResponse(response: { credential: string }) {\n    \u002F\u002F Send token to backend for verification\n    const result = await fetch('\u002Fapi\u002Fauth\u002Fgoogle', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      credentials: 'include',\n      body: JSON.stringify({ token: response.credential }),\n    });\n\n    if (result.ok) {\n      window.location.href = '\u002Fdashboard';\n    }\n  }\n\n  return \u003Cdiv id=\"google-signin\" \u002F>;\n}\n```\n\n### NextAuth.js (Recommended for Next.js)\n\n```typescript\n\u002F\u002F pages\u002Fapi\u002Fauth\u002F[...nextauth].ts or app\u002Fapi\u002Fauth\u002F[...nextauth]\u002Froute.ts\nimport NextAuth from 'next-auth';\nimport GoogleProvider from 'next-auth\u002Fproviders\u002Fgoogle';\nimport CredentialsProvider from 'next-auth\u002Fproviders\u002Fcredentials';\n\nexport const authOptions = {\n  providers: [\n    GoogleProvider({\n      clientId: process.env.GOOGLE_CLIENT_ID!,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,\n    }),\n    CredentialsProvider({\n      name: 'Credentials',\n      credentials: {\n        email: { label: 'Email', type: 'email' },\n        password: { label: 'Password', type: 'password' },\n      },\n      async authorize(credentials) {\n        \u002F\u002F Verify credentials against your database\n        const user = await verifyCredentials(\n          credentials?.email,\n          credentials?.password\n        );\n        return user ?? null;\n      },\n    }),\n  ],\n  callbacks: {\n    async jwt({ token, user }) {\n      if (user) {\n        token.id = user.id;\n      }\n      return token;\n    },\n    async session({ session, token }) {\n      session.user.id = token.id;\n      return session;\n    },\n  },\n};\n\nexport default NextAuth(authOptions);\n```\n\n```typescript\n\u002F\u002F Usage in components\nimport { useSession, signIn, signOut } from 'next-auth\u002Freact';\n\nfunction AuthButton() {\n  const { data: session, status } = useSession();\n\n  if (status === 'loading') {\n    return \u003CSpinner \u002F>;\n  }\n\n  if (session) {\n    return (\n      \u003Cdiv>\n        \u003Cspan>Signed in as {session.user?.email}\u003C\u002Fspan>\n        \u003Cbutton onClick={() => signOut()}>Sign out\u003C\u002Fbutton>\n      \u003C\u002Fdiv>\n    );\n  }\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => signIn('google')}>Sign in with Google\u003C\u002Fbutton>\n      \u003Cbutton onClick={() => signIn('credentials')}>Sign in\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n---\n\n## Protected Routes\n\n### React Router\n\n```typescript\nimport { Navigate, Outlet, useLocation } from 'react-router-dom';\nimport { useAuth } from '@\u002Fcontexts\u002Fauth';\n\nfunction ProtectedRoute() {\n  const { isAuthenticated, isLoading } = useAuth();\n  const location = useLocation();\n\n  if (isLoading) {\n    return \u003CLoadingScreen \u002F>;\n  }\n\n  if (!isAuthenticated) {\n    \u002F\u002F Redirect to login, preserving intended destination\n    return \u003CNavigate to=\"\u002Flogin\" state={{ from: location }} replace \u002F>;\n  }\n\n  return \u003COutlet \u002F>;\n}\n\n\u002F\u002F Usage in router\n\u003CRoutes>\n  \u003CRoute path=\"\u002Flogin\" element={\u003CLoginPage \u002F>} \u002F>\n  \u003CRoute element={\u003CProtectedRoute \u002F>}>\n    \u003CRoute path=\"\u002Fdashboard\" element={\u003CDashboard \u002F>} \u002F>\n    \u003CRoute path=\"\u002Fsettings\" element={\u003CSettings \u002F>} \u002F>\n  \u003C\u002FRoute>\n\u003C\u002FRoutes>\n```\n\n### Next.js App Router\n\n```typescript\n\u002F\u002F middleware.ts\nimport { NextResponse } from 'next\u002Fserver';\nimport type { NextRequest } from 'next\u002Fserver';\n\nexport function middleware(request: NextRequest) {\n  const token = request.cookies.get('auth-token');\n\n  if (!token && request.nextUrl.pathname.startsWith('\u002Fdashboard')) {\n    return NextResponse.redirect(new URL('\u002Flogin', request.url));\n  }\n\n  return NextResponse.next();\n}\n\nexport const config = {\n  matcher: ['\u002Fdashboard\u002F:path*', '\u002Fsettings\u002F:path*'],\n};\n```\n\n```typescript\n\u002F\u002F app\u002Fdashboard\u002Flayout.tsx\nimport { redirect } from 'next\u002Fnavigation';\nimport { getServerSession } from 'next-auth';\nimport { authOptions } from '@\u002Fapp\u002Fapi\u002Fauth\u002F[...nextauth]\u002Froute';\n\nexport default async function DashboardLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  const session = await getServerSession(authOptions);\n\n  if (!session) {\n    redirect('\u002Flogin');\n  }\n\n  return \u003C>{children}\u003C\u002F>;\n}\n```\n\n---\n\n## Token Refresh Pattern\n\n```typescript\n\u002F\u002F API client with automatic token refresh\nclass ApiClient {\n  private refreshPromise: Promise\u003Cvoid> | null = null;\n\n  async fetch(url: string, options: RequestInit = {}) {\n    const response = await fetch(url, {\n      ...options,\n      credentials: 'include',\n    });\n\n    if (response.status === 401) {\n      \u002F\u002F Token expired, try refresh\n      await this.refreshToken();\n      \u002F\u002F Retry original request\n      return fetch(url, { ...options, credentials: 'include' });\n    }\n\n    return response;\n  }\n\n  private async refreshToken() {\n    \u002F\u002F Deduplicate refresh requests\n    if (this.refreshPromise) {\n      return this.refreshPromise;\n    }\n\n    this.refreshPromise = fetch('\u002Fapi\u002Fauth\u002Frefresh', {\n      method: 'POST',\n      credentials: 'include',\n    }).then(async (response) => {\n      if (!response.ok) {\n        \u002F\u002F Refresh failed, logout user\n        window.location.href = '\u002Flogin';\n        throw new Error('Session expired');\n      }\n    }).finally(() => {\n      this.refreshPromise = null;\n    });\n\n    return this.refreshPromise;\n  }\n}\n\nexport const api = new ApiClient();\n```\n\n---\n\n## Form Handling\n\n```typescript\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform\u002Fresolvers\u002Fzod';\nimport { z } from 'zod';\n\nconst loginSchema = z.object({\n  email: z.string().email('Invalid email'),\n  password: z.string().min(8, 'Password must be at least 8 characters'),\n});\n\ntype LoginForm = z.infer\u003Ctypeof loginSchema>;\n\nfunction LoginPage() {\n  const { login } = useAuth();\n  const navigate = useNavigate();\n  const location = useLocation();\n\n  const {\n    register,\n    handleSubmit,\n    formState: { errors, isSubmitting },\n    setError,\n  } = useForm\u003CLoginForm>({\n    resolver: zodResolver(loginSchema),\n  });\n\n  async function onSubmit(data: LoginForm) {\n    try {\n      await login(data.email, data.password);\n      \u002F\u002F Redirect to intended page or dashboard\n      const from = location.state?.from?.pathname || '\u002Fdashboard';\n      navigate(from, { replace: true });\n    } catch (error) {\n      setError('root', {\n        message: 'Invalid email or password',\n      });\n    }\n  }\n\n  return (\n    \u003Cform onSubmit={handleSubmit(onSubmit)}>\n      \u003Cdiv>\n        \u003Clabel htmlFor=\"email\">Email\u003C\u002Flabel>\n        \u003Cinput {...register('email')} type=\"email\" id=\"email\" \u002F>\n        {errors.email && \u003Cspan>{errors.email.message}\u003C\u002Fspan>}\n      \u003C\u002Fdiv>\n\n      \u003Cdiv>\n        \u003Clabel htmlFor=\"password\">Password\u003C\u002Flabel>\n        \u003Cinput {...register('password')} type=\"password\" id=\"password\" \u002F>\n        {errors.password && \u003Cspan>{errors.password.message}\u003C\u002Fspan>}\n      \u003C\u002Fdiv>\n\n      {errors.root && \u003Cdiv className=\"error\">{errors.root.message}\u003C\u002Fdiv>}\n\n      \u003Cbutton type=\"submit\" disabled={isSubmitting}>\n        {isSubmitting ? 'Signing in...' : 'Sign in'}\n      \u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n```\n\n---\n\n## Security Best Practices\n\n### CSRF Protection\n\n```typescript\n\u002F\u002F Server: Include CSRF token in response\n\u002F\u002F Client: Send with requests\nasync function fetchWithCSRF(url: string, options: RequestInit = {}) {\n  const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.getAttribute('content');\n\n  return fetch(url, {\n    ...options,\n    headers: {\n      ...options.headers,\n      'X-CSRF-Token': csrfToken || '',\n    },\n    credentials: 'include',\n  });\n}\n```\n\n### Security Headers (Server)\n\n```typescript\n\u002F\u002F Next.js next.config.js\nconst securityHeaders = [\n  {\n    key: 'X-Content-Type-Options',\n    value: 'nosniff',\n  },\n  {\n    key: 'X-Frame-Options',\n    value: 'DENY',\n  },\n  {\n    key: 'X-XSS-Protection',\n    value: '1; mode=block',\n  },\n  {\n    key: 'Strict-Transport-Security',\n    value: 'max-age=31536000; includeSubDomains',\n  },\n];\n\nmodule.exports = {\n  async headers() {\n    return [\n      {\n        source: '\u002F:path*',\n        headers: securityHeaders,\n      },\n    ];\n  },\n};\n```\n\n---\n\n## Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Cookie not sent | Add `credentials: 'include'` to fetch |\n| CORS error with cookies | Server must set `Access-Control-Allow-Credentials: true` |\n| Session lost on refresh | Verify cookie settings (domain, path, secure) |\n| OAuth redirect fails | Check redirect URI in provider console |\n| Token in localStorage stolen | Move to httpOnly cookies |\n\n---\n\n## Backend Integration (FastAPI)\n\n```python\n# For reference: FastAPI auth endpoints\nfrom fastapi import FastAPI, Response, Depends, HTTPException\nfrom fastapi.security import HTTPBearer\n\n@app.post(\"\u002Fapi\u002Fauth\u002Flogin\")\nasync def login(credentials: LoginRequest, response: Response):\n    user = await verify_user(credentials.email, credentials.password)\n    if not user:\n        raise HTTPException(status_code=401, detail=\"Invalid credentials\")\n\n    token = create_jwt_token(user.id)\n    response.set_cookie(\n        key=\"auth-token\",\n        value=token,\n        httponly=True,\n        secure=True,  # HTTPS only\n        samesite=\"lax\",\n        max_age=60 * 60 * 24 * 7,  # 7 days\n    )\n    return {\"user\": user}\n\n@app.post(\"\u002Fapi\u002Fauth\u002Flogout\")\nasync def logout(response: Response):\n    response.delete_cookie(\"auth-token\")\n    return {\"success\": True}\n```\n","# Web Authentication (React)\n\n## Core Patterns\n\n### JWT Token Storage\n\n**Options and trade-offs:**\n\n| Storage | XSS Safe | CSRF Safe | Best For |\n|---------|----------|-----------|----------|\n| httpOnly cookie | Yes | No (needs CSRF token) | Most secure for tokens |\n| localStorage | No | Yes | Simple apps, short-lived tokens |\n| Memory (state) | Yes | Yes | Very short-lived tokens with refresh |\n\n### Cookie-Based Auth (Recommended)\n\n```typescript\n\u002F\u002F API client setup\nconst api = {\n  async login(email: string, password: string) {\n    const response = await fetch('\u002Fapi\u002Fauth\u002Flogin', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      credentials: 'include', \u002F\u002F Important: send\u002Freceive cookies\n      body: JSON.stringify({ email, password }),\n    });\n    return response.json();\n  },\n\n  async logout() {\n    await fetch('\u002Fapi\u002Fauth\u002Flogout', {\n      method: 'POST',\n      credentials: 'include',\n    });\n  },\n\n  async getUser() {\n    const response = await fetch('\u002Fapi\u002Fauth\u002Fme', {\n      credentials: 'include',\n    });\n    if (!response.ok) throw new Error('Not authenticated');\n    return response.json();\n  },\n};\n```\n\n### Auth Context Pattern\n\n```typescript\nimport { createContext, useContext, useEffect, useState, ReactNode } from 'react';\n\ninterface User {\n  id: string;\n  email: string;\n  name: string;\n}\n\ninterface AuthState {\n  user: User | null;\n  isLoading: boolean;\n  isAuthenticated: boolean;\n  login: (email: string, password: string) => Promise\u003Cvoid>;\n  logout: () => Promise\u003Cvoid>;\n  refresh: () => Promise\u003Cvoid>;\n}\n\nconst AuthContext = createContext\u003CAuthState | null>(null);\n\nexport function AuthProvider({ children }: { children: ReactNode }) {\n  const [user, setUser] = useState\u003CUser | null>(null);\n  const [isLoading, setIsLoading] = useState(true);\n\n  useEffect(() => {\n    \u002F\u002F Check auth status on mount\n    checkAuth();\n  }, []);\n\n  async function checkAuth() {\n    try {\n      const userData = await api.getUser();\n      setUser(userData);\n    } catch {\n      setUser(null);\n    } finally {\n      setIsLoading(false);\n    }\n  }\n\n  async function login(email: string, password: string) {\n    const { user } = await api.login(email, password);\n    setUser(user);\n  }\n\n  async function logout() {\n    await api.logout();\n    setUser(null);\n  }\n\n  async function refresh() {\n    await checkAuth();\n  }\n\n  return (\n    \u003CAuthContext.Provider\n      value={{\n        user,\n        isLoading,\n        isAuthenticated: !!user,\n        login,\n        logout,\n        refresh,\n      }}\n    >\n      {children}\n    \u003C\u002FAuthContext.Provider>\n  );\n}\n\nexport function useAuth() {\n  const context = useContext(AuthContext);\n  if (!context) {\n    throw new Error('useAuth must be used within AuthProvider');\n  }\n  return context;\n}\n```\n\n---\n\n## OAuth Patterns\n\n### Google OAuth (Web)\n\n```typescript\n\u002F\u002F Using Google Identity Services\nimport { useEffect } from 'react';\n\ndeclare global {\n  interface Window {\n    google: any;\n  }\n}\n\nfunction GoogleLoginButton() {\n  useEffect(() => {\n    \u002F\u002F Load Google Identity Services script\n    const script = document.createElement('script');\n    script.src = 'https:\u002F\u002Faccounts.google.com\u002Fgsi\u002Fclient';\n    script.async = true;\n    document.body.appendChild(script);\n\n    script.onload = () => {\n      window.google.accounts.id.initialize({\n        client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,\n        callback: handleGoogleResponse,\n      });\n\n      window.google.accounts.id.renderButton(\n        document.getElementById('google-signin'),\n        { theme: 'outline', size: 'large' }\n      );\n    };\n\n    return () => {\n      document.body.removeChild(script);\n    };\n  }, []);\n\n  async function handleGoogleResponse(response: { credential: string }) {\n    \u002F\u002F Send token to backend for verification\n    const result = await fetch('\u002Fapi\u002Fauth\u002Fgoogle', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      credentials: 'include',\n      body: JSON.stringify({ token: response.credential }),\n    });\n\n    if (result.ok) {\n      window.location.href = '\u002Fdashboard';\n    }\n  }\n\n  return \u003Cdiv id=\"google-signin\" \u002F>;\n}\n```\n\n### NextAuth.js (Recommended for Next.js)\n\n```typescript\n\u002F\u002F pages\u002Fapi\u002Fauth\u002F[...nextauth].ts or app\u002Fapi\u002Fauth\u002F[...nextauth]\u002Froute.ts\nimport NextAuth from 'next-auth';\nimport GoogleProvider from 'next-auth\u002Fproviders\u002Fgoogle';\nimport CredentialsProvider from 'next-auth\u002Fproviders\u002Fcredentials';\n\nexport const authOptions = {\n  providers: [\n    GoogleProvider({\n      clientId: process.env.GOOGLE_CLIENT_ID!,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,\n    }),\n    CredentialsProvider({\n      name: 'Credentials',\n      credentials: {\n        email: { label: 'Email', type: 'email' },\n        password: { label: 'Password', type: 'password' },\n      },\n      async authorize(credentials) {\n        \u002F\u002F Verify credentials against your database\n        const user = await verifyCredentials(\n          credentials?.email,\n          credentials?.password\n        );\n        return user ?? null;\n      },\n    }),\n  ],\n  callbacks: {\n    async jwt({ token, user }) {\n      if (user) {\n        token.id = user.id;\n      }\n      return token;\n    },\n    async session({ session, token }) {\n      session.user.id = token.id;\n      return session;\n    },\n  },\n};\n\nexport default NextAuth(authOptions);\n```\n\n```typescript\n\u002F\u002F Usage in components\nimport { useSession, signIn, signOut } from 'next-auth\u002Freact';\n\nfunction AuthButton() {\n  const { data: session, status } = useSession();\n\n  if (status === 'loading') {\n    return \u003CSpinner \u002F>;\n  }\n\n  if (session) {\n    return (\n      \u003Cdiv>\n        \u003Cspan>Signed in as {session.user?.email}\u003C\u002Fspan>\n        \u003Cbutton onClick={() => signOut()}>Sign out\u003C\u002Fbutton>\n      \u003C\u002Fdiv>\n    );\n  }\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => signIn('google')}>Sign in with Google\u003C\u002Fbutton>\n      \u003Cbutton onClick={() => signIn('credentials')}>Sign in\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n---\n\n## Protected Routes\n\n### React Router\n\n```typescript\nimport { Navigate, Outlet, useLocation } from 'react-router-dom';\nimport { useAuth } from '@\u002Fcontexts\u002Fauth';\n\nfunction ProtectedRoute() {\n  const { isAuthenticated, isLoading } = useAuth();\n  const location = useLocation();\n\n  if (isLoading) {\n    return \u003CLoadingScreen \u002F>;\n  }\n\n  if (!isAuthenticated) {\n    \u002F\u002F Redirect to login, preserving intended destination\n    return \u003CNavigate to=\"\u002Flogin\" state={{ from: location }} replace \u002F>;\n  }\n\n  return \u003COutlet \u002F>;\n}\n\n\u002F\u002F Usage in router\n\u003CRoutes>\n  \u003CRoute path=\"\u002Flogin\" element={\u003CLoginPage \u002F>} \u002F>\n  \u003CRoute element={\u003CProtectedRoute \u002F>}>\n    \u003CRoute path=\"\u002Fdashboard\" element={\u003CDashboard \u002F>} \u002F>\n    \u003CRoute path=\"\u002Fsettings\" element={\u003CSettings \u002F>} \u002F>\n  \u003C\u002FRoute>\n\u003C\u002FRoutes>\n```\n\n### Next.js App Router\n\n```typescript\n\u002F\u002F middleware.ts\nimport { NextResponse } from 'next\u002Fserver';\nimport type { NextRequest } from 'next\u002Fserver';\n\nexport function middleware(request: NextRequest) {\n  const token = request.cookies.get('auth-token');\n\n  if (!token && request.nextUrl.pathname.startsWith('\u002Fdashboard')) {\n    return NextResponse.redirect(new URL('\u002Flogin', request.url));\n  }\n\n  return NextResponse.next();\n}\n\nexport const config = {\n  matcher: ['\u002Fdashboard\u002F:path*', '\u002Fsettings\u002F:path*'],\n};\n```\n\n```typescript\n\u002F\u002F app\u002Fdashboard\u002Flayout.tsx\nimport { redirect } from 'next\u002Fnavigation';\nimport { getServerSession } from 'next-auth';\nimport { authOptions } from '@\u002Fapp\u002Fapi\u002Fauth\u002F[...nextauth]\u002Froute';\n\nexport default async function DashboardLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  const session = await getServerSession(authOptions);\n\n  if (!session) {\n    redirect('\u002Flogin');\n  }\n\n  return \u003C>{children}\u003C\u002F>;\n}\n```\n\n---\n\n## Token Refresh Pattern\n\n```typescript\n\u002F\u002F API client with automatic token refresh\nclass ApiClient {\n  private refreshPromise: Promise\u003Cvoid> | null = null;\n\n  async fetch(url: string, options: RequestInit = {}) {\n    const response = await fetch(url, {\n      ...options,\n      credentials: 'include',\n    });\n\n    if (response.status === 401) {\n      \u002F\u002F Token expired, try refresh\n      await this.refreshToken();\n      \u002F\u002F Retry original request\n      return fetch(url, { ...options, credentials: 'include' });\n    }\n\n    return response;\n  }\n\n  private async refreshToken() {\n    \u002F\u002F Deduplicate refresh requests\n    if (this.refreshPromise) {\n      return this.refreshPromise;\n    }\n\n    this.refreshPromise = fetch('\u002Fapi\u002Fauth\u002Frefresh', {\n      method: 'POST',\n      credentials: 'include',\n    }).then(async (response) => {\n      if (!response.ok) {\n        \u002F\u002F Refresh failed, logout user\n        window.location.href = '\u002Flogin';\n        throw new Error('Session expired');\n      }\n    }).finally(() => {\n      this.refreshPromise = null;\n    });\n\n    return this.refreshPromise;\n  }\n}\n\nexport const api = new ApiClient();\n```\n\n---\n\n## Form Handling\n\n```typescript\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform\u002Fresolvers\u002Fzod';\nimport { z } from 'zod';\n\nconst loginSchema = z.object({\n  email: z.string().email('Invalid email'),\n  password: z.string().min(8, 'Password must be at least 8 characters'),\n});\n\ntype LoginForm = z.infer\u003Ctypeof loginSchema>;\n\nfunction LoginPage() {\n  const { login } = useAuth();\n  const navigate = useNavigate();\n  const location = useLocation();\n\n  const {\n    register,\n    handleSubmit,\n    formState: { errors, isSubmitting },\n    setError,\n  } = useForm\u003CLoginForm>({\n    resolver: zodResolver(loginSchema),\n  });\n\n  async function onSubmit(data: LoginForm) {\n    try {\n      await login(data.email, data.password);\n      \u002F\u002F Redirect to intended page or dashboard\n      const from = location.state?.from?.pathname || '\u002Fdashboard';\n      navigate(from, { replace: true });\n    } catch (error) {\n      setError('root', {\n        message: 'Invalid email or password',\n      });\n    }\n  }\n\n  return (\n    \u003Cform onSubmit={handleSubmit(onSubmit)}>\n      \u003Cdiv>\n        \u003Clabel htmlFor=\"email\">Email\u003C\u002Flabel>\n        \u003Cinput {...register('email')} type=\"email\" id=\"email\" \u002F>\n        {errors.email && \u003Cspan>{errors.email.message}\u003C\u002Fspan>}\n      \u003C\u002Fdiv>\n\n      \u003Cdiv>\n        \u003Clabel htmlFor=\"password\">Password\u003C\u002Flabel>\n        \u003Cinput {...register('password')} type=\"password\" id=\"password\" \u002F>\n        {errors.password && \u003Cspan>{errors.password.message}\u003C\u002Fspan>}\n      \u003C\u002Fdiv>\n\n      {errors.root && \u003Cdiv className=\"error\">{errors.root.message}\u003C\u002Fdiv>}\n\n      \u003Cbutton type=\"submit\" disabled={isSubmitting}>\n        {isSubmitting ? 'Signing in...' : 'Sign in'}\n      \u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n```\n\n---\n\n## Security Best Practices\n\n### CSRF Protection\n\n```typescript\n\u002F\u002F Server: Include CSRF token in response\n\u002F\u002F Client: Send with requests\nasync function fetchWithCSRF(url: string, options: RequestInit = {}) {\n  const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.getAttribute('content');\n\n  return fetch(url, {\n    ...options,\n    headers: {\n      ...options.headers,\n      'X-CSRF-Token': csrfToken || '',\n    },\n    credentials: 'include',\n  });\n}\n```\n\n### Security Headers (Server)\n\n```typescript\n\u002F\u002F Next.js next.config.js\nconst securityHeaders = [\n  {\n    key: 'X-Content-Type-Options',\n    value: 'nosniff',\n  },\n  {\n    key: 'X-Frame-Options',\n    value: 'DENY',\n  },\n  {\n    key: 'X-XSS-Protection',\n    value: '1; mode=block',\n  },\n  {\n    key: 'Strict-Transport-Security',\n    value: 'max-age=31536000; includeSubDomains',\n  },\n];\n\nmodule.exports = {\n  async headers() {\n    return [\n      {\n        source: '\u002F:path*',\n        headers: securityHeaders,\n      },\n    ];\n  },\n};\n```\n\n---\n\n## Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Cookie not sent | Add `credentials: 'include'` to fetch |\n| CORS error with cookies | Server must set `Access-Control-Allow-Credentials: true` |\n| Session lost on refresh | Verify cookie settings (domain, path, secure) |\n| OAuth redirect fails | Check redirect URI in provider console |\n| Token in localStorage stolen | Move to httpOnly cookies |\n\n---\n\n## Backend Integration (FastAPI)\n\n```python\n# For reference: FastAPI auth endpoints\nfrom fastapi import FastAPI, Response, Depends, HTTPException\nfrom fastapi.security import HTTPBearer\n\n@app.post(\"\u002Fapi\u002Fauth\u002Flogin\")\nasync def login(credentials: LoginRequest, response: Response):\n    user = await verify_user(credentials.email, credentials.password)\n    if not user:\n        raise HTTPException(status_code=401, detail=\"Invalid credentials\")\n\n    token = create_jwt_token(user.id)\n    response.set_cookie(\n        key=\"auth-token\",\n        value=token,\n        httponly=True,\n        secure=True,  # HTTPS only\n        samesite=\"lax\",\n        max_age=60 * 60 * 24 * 7,  # 7 days\n    )\n    return {\"user\": user}\n\n@app.post(\"\u002Fapi\u002Fauth\u002Flogout\")\nasync def logout(response: Response):\n    response.delete_cookie(\"auth-token\")\n    return {\"success\": True}\n```\n",{"name":5,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Faiskillstore\u002Fmarketplace\u002Fcjharmath\u002Fweb-auth",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill web-auth",{"tool":55,"command":56},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill web-auth",{"tool":58,"command":59},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill web-auth","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Fcjharmath\u002Fweb-auth\u002FSKILL.md",true,[63],{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":68},"skill-report.json","REFERENCE","参考文档",13979,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Fcjharmath\u002Fweb-auth\u002Fskill-report.json",[70,79,88,96,102,108],{"skillNo":71,"name":72,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":35},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[76,77,78],"model","model hierarchy","model hierarchy skill",{"skillNo":80,"name":81,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":35},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[85,86,87],"MCP","zoom","zoom mcp",{"skillNo":89,"name":90,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":35},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[94,95,31,86],"sdk","zoom apps sdk",{"skillNo":97,"name":98,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":35},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[98],{"skillNo":103,"name":104,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":35},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[104],{"skillNo":109,"name":110,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":35},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[110]]