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.

Next.js SDK

Official Next.js SDK for AuthSafe with full support for App Router and Pages Router.

Overview

The authsafe-nextjs SDK provides seamless OAuth 2.1 and OpenID Connect authentication for Next.js applications. It includes both client-side and server-side utilities for modern Next.js development.
Full Stack Authentication
Client-side React hooks, server-side auth helpers, route protection middleware, and pre-built UI components - everything you need for Next.js authentication.

Features

  • ✅ App Router & Pages Router - Full support for both Next.js paradigms
  • ✅ Server Components - SSR-friendly authentication with getAuth()
  • ✅ Client Hooks - useAuth(), useSession(), useMfa() for reactive UI
  • ✅ Route Protection - Middleware for protecting entire route groups
  • ✅ Pre-built UI - SignInButton, SignOutButton, UserButton, Profile
  • ✅ Automatic Token Refresh - Seamless session management
  • ✅ TypeScript - Full type safety out of the box
  • ✅ MFA Support - TOTP, Email OTP, WebAuthn
  • ✅ Secure Cookies - HttpOnly, SameSite, Secure by default

Installation

npm install authsafe-nextjs
# or
yarn add authsafe-nextjs
# or
pnpm add authsafe-nextjs

Quick Start

1. Environment Variables

Create a .env.local file:
NEXT_PUBLIC_AUTHSAFE_CLIENT_ID=your_client_id
NEXT_PUBLIC_AUTHSAFE_DOMAIN=https://auth.yourapp.com
AUTHSAFE_CLIENT_SECRET=your_client_secret # For API routes

2. Root Layout (App Router)

Wrap your app with AuthProvider:
// app/layout.tsx
import { AuthProvider } from 'authsafe-nextjs/client';
import { getAuth, 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,
});

export default async function RootLayout({ children }) {
  const session = await getAuth();

  return (
    <html lang="en">
      <body>
        <AuthProvider
          config={{
            clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
            domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
          }}
          initialSession={session}
        >
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

3. API Routes

Create authentication endpoints:
// app/api/auth/signin/route.ts
import { handleSignIn } from 'authsafe-nextjs/server';

export async function GET(request: Request) {
  return handleSignIn(request);
}
// app/api/auth/callback/route.ts
import { handleCallback } from 'authsafe-nextjs/server';

export async function GET(request: Request) {
  return handleCallback(request);
}
// app/api/auth/logout/route.ts
import { handleLogout } from 'authsafe-nextjs/server';

export async function POST(request: Request) {
  return handleLogout(request);
}
// app/api/auth/refresh/route.ts
import { handleRefresh } from 'authsafe-nextjs/server';

export async function POST(request: Request) {
  return handleRefresh(request);
}

4. Use in Client Components

'use client';

import { useAuth, SignInButton, SignOutButton } from 'authsafe-nextjs/client';

export function Header() {
  const { isAuthenticated, user } = useAuth();

  if (!isAuthenticated) {
    return <SignInButton className="btn-primary">Sign In</SignInButton>;
  }

  return (
    <div>
      <p>Welcome, {user?.email}</p>
      <SignOutButton>Sign Out</SignOutButton>
    </div>
  );
}

5. Use in Server Components

// app/dashboard/page.tsx
import { getAuth } from 'authsafe-nextjs/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const session = await getAuth();

  if (!session) {
    redirect('/api/auth/signin');
  }

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Logged in as: {session.email}</p>
    </div>
  );
}

SDK Reference

Client-Side (Import from authsafe-nextjs/client)

| Export | Type | Description | | ---------------------------------------------------------------- | --------- | ------------------------------------------ | | AuthProvider | Component | Context provider for authentication state | | useAuth() | Hook | Main authentication hook with sign in/out | | useSession() | Hook | Access current user session | | useMfa() | Hook | MFA management (register, confirm, remove) | | SignInButton | Component | Pre-styled sign in button | | SignOutButton | Component | Pre-styled sign out button | | UserButton | Component | User dropdown with sign out | | Profile | Component | Full profile management UI |

Server-Side (Import from authsafe-nextjs/server)

| Export | Type | Description | | ----------------------------------------------------------------------- | -------- | ---------------------------------- | | initAuthSafe() | Function | Initialize SDK configuration | | getAuth() | Function | Get session in Server Components | | requireAuth() | Function | Require authentication or throw | | getAccessToken() | Function | Get access token for API calls | | createAuthMiddleware() | Function | Create route protection middleware | | handleSignIn() | Function | Sign in API handler | | handleCallback() | Function | OAuth callback handler | | handleLogout() | Function | Logout API handler | | handleRefresh() | Function | Token refresh handler |

Architecture

┌─────────────────────────────────────┐
│         Client Components           │
│  (useAuth, SignInButton, Profile)   │
└──────────────┬──────────────────────┘
               │
               ├──> AuthProvider (React Context)
               │
               ├──> API Routes (/api/auth/*)
               │     ├─ signin
               │     ├─ callback
               │     ├─ logout
               │     └─ refresh
               │
               ├──> Server Components (getAuth)
               │
               └──> Middleware (Route Protection)

                     ↓

               Secure HttpOnly Cookies
               (id_token, access_token, refresh_token)

Examples

Protected Server Component

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

Client Component with Auth

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function UserProfile() {
  const { isAuthenticated, user, signOut } = useAuth();

  if (!isAuthenticated) return null;

  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  );
}

Route Protection with Middleware

// middleware.ts
import { createAuthMiddleware } from 'authsafe-nextjs/server';

export default createAuthMiddleware({
  authConfig: {
    clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
    domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
  },
  protectedRoutes: ['/dashboard', '/profile', /^\/admin/],
  publicRoutes: ['/'],
  signInUrl: '/api/auth/signin',
});

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

MFA Management

'use client';

import { useMfa } from 'authsafe-nextjs/client';
import { useEffect } from 'react';

export function MfaSettings() {
  const { methods, fetchMethods, registerMethod } = useMfa();

  useEffect(() => {
    fetchMethods();
  }, []);

  const handleEnableTOTP = async () => {
    const { qrCode } = await registerMethod('TOTP');
    // Display QR code to user
  };

  return (
    <div>
      <h2>MFA Methods</h2>
      {methods.map((method) => (
        <div key={method.id}>{method.type}</div>
      ))}
      <button onClick={handleEnableTOTP}>Enable TOTP</button>
    </div>
  );
}

Browser Support

  • Chrome/Edge ≥ 90
  • Firefox ≥ 88
  • Safari ≥ 14
  • All modern mobile browsers

Next Steps

  • Set up AuthProvider - Configure the authentication context
  • Use the useAuth() hook - Add authentication to client components
  • Server-side authentication - Protect Server Components
  • Route protection - Secure entire routes with middleware
  • API handlers - Set up authentication endpoints

Need Help?

  • 📘 API Reference - Complete API documentation
  • 💬 Contact Support - Get help from our team
  • 📝 Quick Start Guide - Step-by-step tutorial