nextauthz
v1.3.40
Published
** NextAuthZ provides:
Readme
Auth System Documentation
Overview
** NextAuthZ provides:
** Global auth state
** Token persistence
** Typed AuthProvider & useAuth
** Route protection (AuthGuard)
** Role-based protection (RoleGuard)
** Configurable storage system
** Configurable role extraction (rolePath)
Works perfectly with Next.js App Router.
Installation
npm install nextauthz
Setup
1️⃣ Create Your Auth Instance
Because NextAuthZ uses a factory pattern, you must create your own auth instance.
// src/lib/auth.ts
import { createAuthContext } from 'nextauthz'
export const {
AuthProvider,
useAuth,
} = createAuthContext({
storage: 'cookie', // 'localStorage' | 'sessionStorage' | 'cookie'
tokenKey: 'access_token', // optional (default: 'access_token')
rolePath: 'account_type', // optional (default: 'role')
})Available Options
| Option | Type | Default | Description |
| ---------- | ------------------------------------------------ | ---------------- | ------------------------------------- |
| storage | 'localStorage' \| 'sessionStorage' \| 'cookie' | 'cookie' | Where tokens are stored |
| tokenKey | string | 'access_token' | Key used for primary token |
| rolePath | string | 'role' | Path to extract role from user object |
2️⃣ Wrap Your App
Wrap your application with AuthProvider to provide global auth state (user, loading, error) and helper functions (login, logout, setUser).
// app/layout.tsx
import { AuthProvider } from '@/lib/auth'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return <AuthProvider>{children}</AuthProvider>
}useAuth Hook
import { useAuth } from '@/lib/auth'
const {
user,
role,
isAuthenticated,
isAuthChecked,
login,
logout,
setUser,
} = useAuth()Available Properties
| Name | Type | Description |
| ----------------- | ------------------------------------ | ---------------------------------------- |
| user | User \| null | Current authenticated user |
| role | string \| null | Extracted user role |
| isAuthenticated | boolean | True if logged in |
| isAuthChecked | boolean | True when auth hydration is complete |
| login | (tokens, userData?, role?) => void | Save tokens + optionally set user + role |
| logout | () => void | Clears tokens and resets auth |
| setUser | (user \| null) => void | Manually update user |
Example: Logging In
const { login } = useAuth()
const handleLogin = async () => {
const tokens = {
access_token: 'abc123',
refresh_token: 'xyz789',
}
const user = {
id: '1',
name: 'John',
account_type: 'admin',
}
login(tokens, user)
}If rolePath: 'account_type' is configured, role is automatically extracted.
You can also override it manually:
login(tokens, user, 'admin')Logging Out
const { logout } = useAuth()
const handleLogin = async () => {
logout()
router.replace('/authentication/login');
}AuthGuard
Purpose
Protect pages so only authenticated users can access them.
Props
| Name | Type | Default | Description |
| ------------ | ----------- | -------- | ---------------------------------- |
| children | ReactNode | required | Content to render if authenticated |
| redirectTo | string | /login | Redirect if not authenticated |
| fallback | ReactNode | null | Optional loading UI |
Usage Example
import { AuthGuard } from 'nextauthz'
function DashboardPage() {
return (
<AuthGuard fallback={<p>Loading...</p>}>
<h1>Dashboard</h1>
</AuthGuard>
)
}Behavior:
** Waits for isAuthChecked
** Redirects to redirectTo value if not authenticated
** Renders children if authenticatedRoleGuard
Restrict access based on role.
Props
| Name | Type | Default | Description |
| -------------- | ----------- | --------------- | ---------------------------- |
| children | ReactNode | required | Content to render |
| allowedRoles | string[] | required | Allowed roles |
| redirectTo | string | /unauthorized | Redirect if role not allowed |
| fallback | ReactNode | null | Optional loading UI |
Usage Example
import { RoleGuard } from 'nextauthz'
export default function AdminPage() {
return (
<RoleGuard allowedRoles={['admin']} fallback={<p>Checking role...</p>}>
<h1>Admin Dashboard</h1>
</RoleGuard>
)
}Behavior:
** Waits for isAuthChecked
** Redirects if role not in allowedRoles
** Blocks rendering if unauthorizedStorage Options
You can configure token storage:
| Storage Type | Behavior |
| ---------------- | ---------------------- |
| localStorage | Persists until cleared |
| sessionStorage | Clears on tab close |
| cookie | Cookie-based (default) |
Role Path Examples
Given this user:
{
id: "1",
email: "[email protected]",
account_type: "artist"
}Use:
rolePath: 'account_type'Nested example:
{
profile: {
role: 'admin'
}
}Use:
rolePath: 'profile.role'Why NextAuthZ?
** Zero boilerplate
** Fully typed
** Storage configurable
** Clean architecture
** Works with Next.js App Router
** Lightweight
** No opinionated backend
** Backend agnostic
** Factory-based (multiple auth instances supported)