🚀. 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

latest
Source
npmnpm
Version
0.4.0
Version published
Weekly downloads
20
-62.96%
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

For a complete tutorial, see the Next.js integration guide on Authgear Docs, or explore the example project on GitHub.

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!,
  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 in Server Actions

Use auth() to get the session (including a fresh access token) without fetching user info. This is the right choice for Server Actions that need to call a downstream API on behalf of the user — auth() will auto-refresh the token if expired before returning it.

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

export async function callMyApiAction() {
  const session = await auth(authgearConfig);
  if (session.state !== SessionState.Authenticated || !session.accessToken) {
    throw new Error("Not authenticated");
  }

  // session.accessToken is always fresh — auto-refreshed if it was expired
  const res = await fetch("https://api.example.com/data", {
    headers: { Authorization: `Bearer ${session.accessToken}` },
  });
  return res.json();
}

API Reference

@authgear/nextjs

ExportKindValuesDescription
createAuthgearHandlers(config)FunctionReturns { GET, POST } for app/api/auth/[...authgear]/route.ts
PromptOptionEnum"login" | "none"Convenience constants for the OIDC prompt parameter. Pass to signIn({ prompt: PromptOption.Login }) to force the login form for a specific sign-in call.

@authgear/nextjs/server

ExportDescription
auth(config)Returns the current Session, auto-refreshes access token if expired
currentUser(config)Returns UserInfo | null, auto-refreshes access token if expired
verifyAccessToken(token, config)Verifies a JWT Bearer token with JWKS, returns JWTPayload
getOpenURL(page, config)Returns a URL to open an Authgear page (e.g. Page.Settings) with the user pre-authenticated

@authgear/nextjs/client

ExportDescription
<AuthgearProvider>React context provider, must wrap the app
useAuthgear()Returns { state, user, isLoaded, isAuthenticated, signIn, signOut, openPage }
useUser()Returns UserInfo | null
<SignInButton>Button that calls signIn() on click
<SignOutButton>Button that calls signOut() on click
<UserSettingsButton>Button that opens Authgear account settings in a new tab

AuthgearProvider props:

PropDefaultDescription
openPagePath"/api/auth/open"Route used by openPage() and <UserSettingsButton> to pre-authenticate and redirect to an Authgear page

SignInOptions

Options accepted by signIn() (from useAuthgear()) and the signInOptions prop on <SignInButton>.

FieldTypeRequiredDefaultDescription
returnTostringNoPath to redirect to after sign-in.
loginPathstringNo"/api/auth/login"Override the login route for this call.
promptstringNoOIDC prompt value for this sign-in call. Use PromptOption.Login to force the login form. Overrides the global isSSOEnabled setting.

@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)
postLogoutRedirectURIWhere to redirect after logout. Defaults to "/"
scopesOAuth scopes. Defaults to ["openid", "offline_access", "https://authgear.com/scopes/full-userinfo"]
isSSOEnabledWhen false, always shows the Authgear login form (prompt=login), even if the user has an existing Authgear session. Recommended for single-app deployments. Defaults to true
cookieNameSession cookie name. Defaults to "authgear.session"

Roadmap

This SDK is actively maintained. Feature requests and contributions are welcome via GitHub Issues.

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 19 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