import {
initAuthSafe,
getAuth,
requireAuth,
currentUser,
getAccessToken,
hasScope,
hasScopes,
} from 'authsafe-nextjs/server';function initAuthSafe(config: AuthSafeConfig): void;| Property | Type | Required | Description |
|---|---|---|---|
clientId | string | Yes | OAuth client ID from AuthSafe |
domain | string | Yes | AuthSafe domain URL |
clientSecret | string | No | Client secret (for API routes) |
redirectUri | string | No | Callback URL (default: /api/auth/callback) |
scopes | string[] | No | Default scopes |
// app/layout.tsx
import { initAuthSafe } from 'authsafe-nextjs/server';
initAuthSafe({
clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
clientSecret: process.env.AUTHSAFE_CLIENT_SECRET,
scopes: ['openid', 'email', 'profile', 'offline_access'],
});null if not authenticated or token is expired.
async function getAuth(): Promise<AuthSession | null>;interface AuthSession {
userId: string;
email: string;
name?: string;
emailVerified: boolean;
organizationId: string;
issuedAt: number;
expiresAt: number;
}// app/dashboard/page.tsx
import { getAuth } from 'authsafe-nextjs/server';
export default async function DashboardPage() {
const session = await getAuth();
if (!session) {
return <div>Not authenticated</div>;
}
return (
<div>
<h1>Welcome, {session.email}</h1>
<p>User ID: {session.userId}</p>
</div>
);
}'use server';
import { getAuth } from 'authsafe-nextjs/server';
export async function updateProfile(formData: FormData) {
const session = await getAuth();
if (!session) {
throw new Error('Not authenticated');
}
const name = formData.get('name');
// Update profile...
return { success: true };
}// app/api/user/route.ts
import { getAuth } from 'authsafe-nextjs/server';
export async function GET() {
const session = await getAuth();
if (!session) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
return Response.json({ user: session });
}getAuth(), but throws an error if not authenticated. Use when authentication is mandatory.
async function requireAuth(): Promise<AuthSession>;// app/protected/page.tsx
import { requireAuth } from 'authsafe-nextjs/server';
export default async function ProtectedPage() {
const session = await requireAuth(); // Throws if not authenticated
return <div>Hello, {session.email}</div>;
}getAuth(). Use whichever name you prefer.
async function currentUser(): Promise<AuthSession | null>;import { currentUser } from 'authsafe-nextjs/server';
export default async function ProfilePage() {
const user = await currentUser();
if (!user) {
return <div>Please sign in</div>;
}
return <div>Profile for {user.email}</div>;
}async function getAccessToken(): Promise<string | null>;import { getAccessToken } from 'authsafe-nextjs/server';
export async function fetchUserData() {
const token = await getAccessToken();
if (!token) {
throw new Error('Not authenticated');
}
const response = await fetch('https://api.example.com/user', {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.json();
}'use server';
import { getAccessToken } from 'authsafe-nextjs/server';
export async function callExternalAPI() {
const token = await getAccessToken();
if (!token) {
return { error: 'Not authenticated' };
}
const response = await fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
return response.json();
}async function hasScope(scope: string): Promise<boolean>;import { hasScope } from 'authsafe-nextjs/server';
export default async function AdminPage() {
const isAdmin = await hasScope('admin');
if (!isAdmin) {
return <div>Access denied</div>;
}
return <div>Admin Panel</div>;
}async function hasScopes(scopes: string[]): Promise<boolean>;import { hasScopes } from 'authsafe-nextjs/server';
export default async function ManagementPage() {
const hasPermission = await hasScopes([
'admin',
'write:users',
'read:analytics',
]);
if (!hasPermission) {
return <div>Insufficient permissions</div>;
}
return <div>User Management</div>;
}// app/dashboard/page.tsx
import { requireAuth, hasScope } from 'authsafe-nextjs/server';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
try {
const session = await requireAuth();
const hasAdminAccess = await hasScope('admin');
return (
<div className="p-8">
<h1 className="text-3xl font-bold mb-4">Dashboard</h1>
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-xl font-semibold mb-2">
Welcome, {session.name}!
</h2>
<p className="text-gray-600">Email: {session.email}</p>
<p className="text-gray-600">
Organization: {session.organizationId}
</p>
{hasAdminAccess && (
<a
href="/admin"
className="mt-4 inline-block text-blue-600 hover:underline"
>
Go to Admin Panel
</a>
)}
</div>
</div>
);
} catch (error) {
redirect('/api/auth/signin?returnTo=/dashboard');
}
}'use server';
import { requireAuth, getAccessToken } from 'authsafe-nextjs/server';
import { revalidatePath } from 'next/cache';
export async function updateUserProfile(formData: FormData) {
const session = await requireAuth();
const token = await getAccessToken();
if (!token) {
return { error: 'No access token' };
}
const name = formData.get('name') as string;
const bio = formData.get('bio') as string;
const response = await fetch(
`${process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN}/api/users/${session.userId}`,
{
method: 'PATCH',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, bio }),
},
);
if (!response.ok) {
return { error: 'Update failed' };
}
revalidatePath('/profile');
return { success: true };
}// app/api/admin/users/route.ts
import { requireAuth, hasScope } from 'authsafe-nextjs/server';
import { NextResponse } from 'next/server';
export async function GET() {
try {
await requireAuth();
const isAdmin = await hasScope('admin');
if (!isAdmin) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Fetch users...
const users = await fetchUsers();
return NextResponse.json({ users });
} catch (error) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
}import { getAuth } from 'authsafe-nextjs/server';
export default async function Page() {
try {
const session = await getAuth();
if (!session) {
// Handle unauthenticated state
return <SignInPrompt />;
}
return <Dashboard user={session} />;
} catch (error) {
// Handle errors (invalid token, network issues, etc.)
return <ErrorPage />;
}
}