AuthIntermediateSSR-safehooks/auth/useAuth.ts

useAuth

Read full auth context.

Import

TypeScript
import { useAuth } from '@/hooks';

API

Signature

useAuth() → AuthContextValue (requires AuthProvider)

When to use

Reading session context anywhere under AuthProvider.

SSR / Next.js

Provider can wrap client layouts; seed isLoading during session hydrate.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useAuth
Editor
function AuthShell({ children }: { children: ReactNode }) {
  return (
    <AuthProvider
      value={{
        user: { id: '1', name: 'Ada', roles: ['admin'], permissions: ['posts:edit'] },
        isAuthenticated: true,
        isLoading: false,
        roles: ['admin'],
        permissions: ['posts:edit'],
        logout: () => console.log('logout'),
      }}
    >
      {children}
    </AuthProvider>
  );
}

function Profile() {
  const { user, logout } = useAuth();
  return (
    <div>
      <p>{user?.name}</p>
      <button onClick={() => void logout?.()}>Logout</button>
    </div>
  );
}
Preview

Implementation source

Full library source for useAuth — copy into your project when you are not installing a package yet.

hooks/auth/useAuth.ts
import { useAuthContext, type AuthContextValue, type AuthUser } from './AuthContext';

/** Access the full auth context. Requires `AuthProvider`. */
export function useAuth<TUser extends AuthUser = AuthUser>(): AuthContextValue<TUser> {
  return useAuthContext<TUser>();
}

Copy-paste example

useAuth.example.tsx
'use client';

import { AuthProvider, useAuth } from '@/hooks';
import type { ReactNode } from 'react';

export function AuthShell({ children }: { children: ReactNode }) {
  return (
    <AuthProvider
      value={{
        user: { id: '1', name: 'Ada', roles: ['admin'], permissions: ['posts:edit'] },
        isAuthenticated: true,
        isLoading: false,
        roles: ['admin'],
        permissions: ['posts:edit'],
        logout: () => console.log('logout'),
      }}
    >
      {children}
    </AuthProvider>
  );
}

export function Profile() {
  const { user, logout } = useAuth();
  return (
    <div>
      <p>{user?.name}</p>
      <button onClick={() => void logout?.()}>Logout</button>
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Wrap the tree with AuthProvider and pass your session shape — keep it generic.
  • Source of truth: open hooks/auth/useAuth.ts for implementation details