RegisterLogin
DocsPricing
RegisterLogin
  • Getting Started
  • Introduction
  • Quick Start
  • SDKs
  • React
  • TypeScript
  • Next.js
  • Express
  • NestJS
  • Python
  • API Reference
  • Support and Resources
  • FAQ
  • Contact Support

AuthSafe

Product

HighlightFeatureIntegrationPricingFAQ

Company

AboutBlogContactSitemap

Developer

DashboardDocumentation

Legal

Terms & ConditionsPrivacyComplianceShippingCancellation

© 2026 AuthSafe. All rights reserved.

We value your privacy

This website uses cookies for anonymous analytics to help us improve your experience. No personal information is stored or shared. You can allow or reject analytics tracking at any time. See our Privacy Policy.

We use cookies for anonymous analytics. No personal info is stored. See our Privacy Policy.

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.
Next.js App Router Optimized
All functions work seamlessly with React Server Components, Server Actions, and the new Next.js caching system.

Import

import {
  initAuthSafe,
  getAuth,
  requireAuth,
  currentUser,
  getAccessToken,
  hasScope,
  hasScopes,
} from 'authsafe-nextjs/server';

initAuthSafe()

Initialize the AuthSafe SDK with your configuration. Call this once in your root layout or app initialization.
function initAuthSafe(config: AuthSafeConfig): void;

Parameters

PropertyTypeRequiredDescription
clientIdstringYesOAuth client ID from AuthSafe
domainstringYesAuthSafe domain URL
clientSecretstringNoClient secret (for API routes)
redirectUristringNoCallback URL (default: /api/auth/callback)
scopesstring[]NoDefault scopes

Example

// 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'],
});

getAuth()

Get the current user session from cookies. Returns null if not authenticated or token is expired.
async function getAuth(): Promise<AuthSession | null>;

Return Type

interface AuthSession {
  userId: string;
  email: string;
  name?: string;
  emailVerified: boolean;
  organizationId: string;
  issuedAt: number;
  expiresAt: number;
}

Examples

Server Component

// 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>
  );
}

Server Action

'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 };
}

API Route

// 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 });
}

requireAuth()

Like getAuth(), but throws an error if not authenticated. Use when authentication is mandatory.
async function requireAuth(): Promise<AuthSession>;

Example

// 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>;
}

currentUser()

Alias for getAuth(). Use whichever name you prefer.
async function currentUser(): Promise<AuthSession | null>;

Example

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>;
}

getAccessToken()

Get the access token for making authenticated API requests.
async function getAccessToken(): Promise<string | null>;

Examples

External API Call

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();
}

Server Action

'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();
}

hasScope()

Check if user has a specific OAuth scope.
async function hasScope(scope: string): Promise<boolean>;

Example

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>;
}

hasScopes()

Check if user has all required scopes.
async function hasScopes(scopes: string[]): Promise<boolean>;

Example

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>;
}

Complete Examples

Protected Server Component

// 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');
  }
}

Server Action with Auth

'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 };
}

API Route with Scope Check

// 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 });
  }
}

Error Handling

All authentication functions handle errors gracefully:
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 />;
  }
}

Related

  • Middleware - Route protection
  • API Handlers - Authentication endpoints
  • useAuth() - Client-side authentication