npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

authsafe-nextjs

v0.0.5

Published

Official Next.js SDK for AuthSafe - OAuth 2.1, OIDC, and MFA for Next.js App Router and Pages Router

Readme

AuthSafe Next.js SDK

The official Next.js SDK for AuthSafe — secure OAuth 2.1, OIDC, and MFA integration for Next.js applications with App Router and Pages Router support.

Features

  • Next.js 14+ & 15+ - Full support for App Router and Pages Router
  • Server Components - Server-side authentication with RSC
  • Middleware - Route protection at the edge
  • Client Hooks - React hooks for authentication state
  • PKCE Flow - Secure authorization code flow with PKCE
  • JWT Validation - JWKS-based token verification with caching
  • MFA Support - TOTP, WebAuthn, Email OTP management
  • Auto Refresh - Automatic token refresh before expiration
  • TypeScript First - Comprehensive type definitions

Installation

npm install authsafe-nextjs

Or with other package managers:

# Yarn
yarn add authsafe-nextjs

# pnpm
pnpm add authsafe-nextjs

Quick Start

1. Environment Variables

# .env.local
AUTHSAFE_CLIENT_ID=your_client_id
AUTHSAFE_CLIENT_SECRET=your_client_secret # Optional for confidential clients
AUTHSAFE_DOMAIN=https://auth.yourapp.com

# Public variables (prefixed with NEXT_PUBLIC_)
NEXT_PUBLIC_AUTHSAFE_CLIENT_ID=your_client_id
NEXT_PUBLIC_AUTHSAFE_DOMAIN=https://auth.yourapp.com

2. Root Layout (App Router)

// app/layout.tsx
import { AuthProvider } from 'authsafe-nextjs/client';
import { getAuth } from 'authsafe-nextjs/server';

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getAuth();

  return (
    <html>
      <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 OAuth callback, sign in, and logout handlers:

// app/api/auth/callback/route.ts
import { handleCallback } from 'authsafe-nextjs/server';

export async function GET(req: NextRequest) {
  return handleCallback(req, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    clientSecret: process.env.AUTHSAFE_CLIENT_SECRET,
    domain: process.env.AUTHSAFE_DOMAIN!,
    redirectUri: `${process.env.APP_URL}/api/auth/callback`,
  });
}
// app/api/auth/signin/route.ts
import { handleSignIn } from 'authsafe-nextjs/server';

export async function GET(req: NextRequest) {
  return handleSignIn(req, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    domain: process.env.AUTHSAFE_DOMAIN!,
    redirectUri: `${process.env.APP_URL}/api/auth/callback`,
  });
}
// app/api/auth/logout/route.ts
import { handleLogout } from 'authsafe-nextjs/server';

export async function POST(req: NextRequest) {
  return handleLogout(req, {
    clientId: process.env.AUTHSAFE_CLIENT_ID!,
    domain: process.env.AUTHSAFE_DOMAIN!,
  });
}

4. Middleware (Optional)

Protect routes automatically:

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

Usage

Server Components

// app/dashboard/page.tsx
import { getAuth, requireAuth } from 'authsafe-nextjs/server';

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

  if (!session) {
    return <div>Not authenticated</div>;
  }

  return <div>Hello {session.email}</div>;
}

// Required auth (throws if not authenticated)
export default async function ProtectedPage() {
  const session = await requireAuth();

  return <div>Protected content for {session.email}</div>;
}

Client Components

'use client';

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

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

  if (isAuthenticated) {
    return (
      <div>
        <span>{user.email}</span>
        <SignOutButton>Logout</SignOutButton>
      </div>
    );
  }

  return <SignInButton>Login</SignInButton>;
}

MFA Management

'use client';

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

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

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

  const handleEnableTOTP = async () => {
    const { qrcode } = await registerMethod('TOTP');
    // Show QR code modal
  };

  return (
    <div>
      <h2>MFA Methods</h2>
      {methods.map((method) => (
        <div key={method.id}>
          {method.type} - {method.isEnabled ? 'Enabled' : 'Disabled'}
        </div>
      ))}
      <button onClick={handleEnableTOTP}>Enable TOTP</button>
    </div>
  );
}

API Reference

Server

  • initAuthSafe(config) - Initialize configuration
  • getAuth() - Get current session (returns null if not authenticated)
  • requireAuth() - Require authentication (throws if not authenticated)
  • currentUser() - Alias for getAuth()
  • getAccessToken() - Get access token for API calls
  • hasScope(scope) - Check if user has specific scope
  • hasScopes(scopes) - Check if user has all required scopes

Client

  • <AuthProvider> - Wrap your app with this provider
  • useAuth() - Main authentication hook
  • useSession() - Get current session
  • useMfa() - MFA management hook
  • <SignInButton> - Pre-built sign in button
  • <SignOutButton> - Pre-built sign out button
  • <UserButton> - User info with dropdown

Middleware

  • createAuthMiddleware(config) - Create route protection middleware
  • authMiddleware(config) - Simple auth status middleware

License

MIT

Support


Made with ❤️ by the AuthSafe team