Server Authentication
Server-side helpers for authentication in Server Components, Server Actions, and API Routes.
Overview
The server-side authentication module provides functions to access user sessions, protect routes, and manage tokens in server contexts. Functions include initAuthSafe(), getAuth(), requireAuth(), currentUser(), getAccessToken(), hasScope(), and hasScopes(). All functions work seamlessly with React Server Components, Server Actions, and the Next.js caching system.
Basic Usage
import { getAuth, requireAuth } from 'authsafe-nextjs/server';
// In a Server Component
export default async function Dashboard() {
const auth = await requireAuth();
return <p>Welcome, {auth.name}</p>;
}
// In a Server Action
async function updateProfile(formData) {
'use server';
const auth = await getAuth();
if (!auth) throw new Error('Unauthorized');
}