🚀. Socket Launch Week Day 3:Socket Firewall Now Blocks Malicious VS Code and Open VSX Extensions.Learn more
Sign In

@authgear/nextjs

Package Overview
Dependencies
Maintainers
5
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@authgear/nextjs

Authgear SDK for Next.js 16 - OAuth authentication, session management, and JWT verification

Source
npmnpm
Version
0.1.1
Version published
Weekly downloads
6
-82.86%
Maintainers
5
Weekly downloads
 
Created
Source

Authgear SDK for Next.js

@authgear/nextjs @authgear/nextjs License

With Authgear SDK for Next.js, you can easily integrate authentication features into your Next.js application — covering both the frontend and backend in one package. In most cases, it involves just a few lines of code to enable multiple authentication methods, such as social logins, passwordless, biometrics logins, one-time-password (OTP) with SMS/WhatsApp, and multi-factor authentication (MFA).

Quick links — 📚 Documentation · 🏁 Getting Started · 🛠️ Troubleshooting · 👥 Contributing

What is Authgear?

Authgear is a highly adaptable identity-as-a-service (IDaaS) platform for web and mobile applications. Authgear makes user authentication easier and faster to implement by integrating it into various types of applications — from single-page web apps to mobile applications to API services.

Key Features

  • Zero-trust authentication architecture with OpenID Connect (OIDC) standard.
  • Easy-to-use interfaces for user registration and login, including email, phone, username as login ID, and password, OTP, magic links, etc.
  • Support for a wide range of identity providers, such as Google, Apple, and Azure Active Directory.
  • Support for Passkeys, biometric login, and Multi-Factor Authentication (MFA) such as SMS/email-based verification and authenticator apps with TOTP.

Requirements

  • Next.js >= 16.0.0
  • React >= 19.0.0
  • Node.js >= 18

Installation

npm install @authgear/nextjs

Getting Started

1. Configure Authgear

Create a config object. The sessionSecret must be at least 32 characters and should be stored in an environment variable.

// lib/authgear.ts
import type { AuthgearConfig } from "@authgear/nextjs";

export const authgearConfig: AuthgearConfig = {
  endpoint: process.env.AUTHGEAR_ENDPOINT!,       // e.g. "https://myapp.authgear.cloud"
  clientID: process.env.AUTHGEAR_CLIENT_ID!,
  clientSecret: process.env.AUTHGEAR_CLIENT_SECRET,  // for confidential clients
  redirectURI: process.env.AUTHGEAR_REDIRECT_URI!,   // e.g. "http://localhost:3000/api/auth/callback"
  sessionSecret: process.env.SESSION_SECRET!,         // min 32 chars
};

2. Add the Route Handler

Create a catch-all route to handle all auth endpoints (/api/auth/login, /api/auth/callback, /api/auth/logout, /api/auth/refresh, /api/auth/userinfo).

// app/api/auth/[...authgear]/route.ts
import { createAuthgearHandlers } from "@authgear/nextjs";
import { authgearConfig } from "@/lib/authgear";

export const { GET, POST } = createAuthgearHandlers(authgearConfig);

3. Add the Provider (Client Components)

Wrap your app with AuthgearProvider to enable client-side hooks and components.

// app/layout.tsx
import { AuthgearProvider } from "@authgear/nextjs/client";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <AuthgearProvider>{children}</AuthgearProvider>
      </body>
    </html>
  );
}

4. Protect Routes with the Proxy (Next.js 16)

Create a proxy.ts file at the root of your project to automatically redirect unauthenticated users and inject auth headers.

// proxy.ts
import { createAuthgearProxy } from "@authgear/nextjs/proxy";
import { authgearConfig } from "@/lib/authgear";

export const proxy = createAuthgearProxy({
  ...authgearConfig,
  protectedPaths: ["/dashboard/*", "/profile/*"],
});

Usage

Client Components

Use the useAuthgear hook or the built-in buttons:

"use client";

import { useAuthgear, SignInButton, SignOutButton } from "@authgear/nextjs/client";

export function NavBar() {
  const { isAuthenticated, isLoaded, user } = useAuthgear();

  if (!isLoaded) return null;

  return isAuthenticated ? (
    <div>
      <span>Welcome, {user?.email}</span>
      <SignOutButton />
    </div>
  ) : (
    <SignInButton />
  );
}

Server Components

Use currentUser() to get the authenticated user in Server Components and Route Handlers.

// app/dashboard/page.tsx
import { currentUser } from "@authgear/nextjs/server";
import { authgearConfig } from "@/lib/authgear";
import { redirect } from "next/navigation";

export default async function DashboardPage() {
  const user = await currentUser(authgearConfig);
  if (!user) redirect("/api/auth/login?returnTo=/dashboard");

  return <h1>Hello, {user.email}</h1>;
}

Protecting API Routes with JWT

Use verifyAccessToken() to validate a Bearer token in API routes.

// app/api/me/route.ts
import { verifyAccessToken } from "@authgear/nextjs/server";
import { authgearConfig } from "@/lib/authgear";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const authHeader = request.headers.get("Authorization");
  const token = authHeader?.replace("Bearer ", "");
  if (!token) return NextResponse.json({ error: "unauthorized" }, { status: 401 });

  try {
    const payload = await verifyAccessToken(token, authgearConfig);
    return NextResponse.json({ sub: payload.sub });
  } catch {
    return NextResponse.json({ error: "invalid_token" }, { status: 401 });
  }
}

Reading the Session

Use auth() to read the raw session (tokens + expiry) without fetching user info.

import { auth } from "@authgear/nextjs/server";
import { authgearConfig } from "@/lib/authgear";

const session = await auth(authgearConfig);
// session.state: SessionState.Authenticated | SessionState.NoSession
// session.accessToken: string | null

API Reference

@authgear/nextjs

ExportDescription
createAuthgearHandlers(config)Returns { GET, POST } for app/api/auth/[...authgear]/route.ts

@authgear/nextjs/server

ExportDescription
auth(config)Returns the current Session from the session cookie
currentUser(config)Returns UserInfo | null, auto-refreshes access token
verifyAccessToken(token, config)Verifies a JWT Bearer token with JWKS, returns JWTPayload

@authgear/nextjs/client

ExportDescription
<AuthgearProvider>React context provider, must wrap the app
useAuthgear()Returns { state, user, isLoaded, isAuthenticated, signIn, signOut }
useUser()Returns UserInfo | null
<SignInButton>Button that calls signIn() on click
<SignOutButton>Button that calls signOut() on click

@authgear/nextjs/proxy

ExportDescription
createAuthgearProxy(options)Returns a Next.js 16 proxy() function

createAuthgearProxy options (extends AuthgearConfig):

OptionDefaultDescription
protectedPaths[]Paths requiring auth, supports * suffix (e.g. "/dashboard/*")
publicPaths["/api/auth/*"]Paths always allowed through
loginPath"/api/auth/login"Where to redirect unauthenticated users

AuthgearConfig

FieldRequiredDescription
endpointAuthgear endpoint, e.g. "https://myapp.authgear.cloud"
clientIDOAuth client ID
redirectURIOAuth callback URL, e.g. "http://localhost:3000/api/auth/callback"
sessionSecretSecret for encrypting session cookie (min 32 chars)
clientSecretOAuth client secret (for confidential clients)
postLogoutRedirectURIWhere to redirect after logout. Defaults to "/"
scopesOAuth scopes. Defaults to ["openid", "offline_access", "https://authgear.com/scopes/full-userinfo"]
cookieNameSession cookie name. Defaults to "authgear.session"

Roadmap

open(page) — Open Authgear Settings Page

Status: pending server-side enablement

The SDK has a planned getOpenURL(page, config) function (modelled after authgear.open(Page.Settings) in the web SDK) that opens the Authgear-hosted settings UI with the current user already authenticated — no re-login required.

How it will work:

// app/dashboard/actions.ts  (Server Action)
"use server";
import { getOpenURL, Page } from "@authgear/nextjs/server";
import { authgearConfig } from "@/lib/authgear";

export async function getSettingsURLAction() {
  return getOpenURL(Page.Settings, authgearConfig);
}
// Client component
const url = await getSettingsURLAction();
window.open(url, "_blank");

Blocker: This feature exchanges the refresh token for an app_session_token via POST /oauth2/app_session_token. The Authgear server must grant the OAuth client "full user access" permission before this endpoint is accessible. Once that server-side configuration is in place, the implementation in src/server.ts can be uncommented and released.

Documentation

Troubleshooting

Please check out the Get Help section for solutions to common issues.

Raise an Issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Contributing

Anyone who wishes to contribute to this project, whether documentation, features, bug fixes, code cleanup, testing, or code reviews, is very much encouraged to do so.

To join, raise your hand on the Authgear Discord server or the GitHub discussions board.

git clone git@github.com:authgear/authgear-sdk-nextjs.git
cd authgear-sdk-nextjs
npm install
npm test

Supported and maintained by

Authgear is a highly adaptable identity-as-a-service (IDaaS) platform for web and mobile applications. To learn more, visit authgear.com.

Keywords

authgear

FAQs

Package last updated on 16 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts