
Product
Socket Firewall Now Blocks Malicious VS Code and Open VSX Extensions
Socket Firewall blocks malicious VS Code and Open VSX extensions before install, protecting developers from compromised editor marketplaces.
@authgear/nextjs
Advanced tools
Authgear SDK for Next.js 16 - OAuth authentication, session management, and JWT verification
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
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.
npm install @authgear/nextjs
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
};
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);
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>
);
}
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/*"],
});
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 />
);
}
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>;
}
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 });
}
}
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
@authgear/nextjs| Export | Description |
|---|---|
createAuthgearHandlers(config) | Returns { GET, POST } for app/api/auth/[...authgear]/route.ts |
@authgear/nextjs/server| Export | Description |
|---|---|
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| Export | Description |
|---|---|
<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| Export | Description |
|---|---|
createAuthgearProxy(options) | Returns a Next.js 16 proxy() function |
createAuthgearProxy options (extends AuthgearConfig):
| Option | Default | Description |
|---|---|---|
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| Field | Required | Description |
|---|---|---|
endpoint | ✓ | Authgear endpoint, e.g. "https://myapp.authgear.cloud" |
clientID | ✓ | OAuth client ID |
redirectURI | ✓ | OAuth callback URL, e.g. "http://localhost:3000/api/auth/callback" |
sessionSecret | ✓ | Secret for encrypting session cookie (min 32 chars) |
clientSecret | OAuth client secret (for confidential clients) | |
postLogoutRedirectURI | Where to redirect after logout. Defaults to "/" | |
scopes | OAuth scopes. Defaults to ["openid", "offline_access", "https://authgear.com/scopes/full-userinfo"] | |
cookieName | Session cookie name. Defaults to "authgear.session" |
open(page) — Open Authgear Settings PageStatus: 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.
Please check out the Get Help section for solutions to common issues.
To provide feedback or report a bug, please raise an issue on our issue tracker.
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
Authgear is a highly adaptable identity-as-a-service (IDaaS) platform for web and mobile applications. To learn more, visit authgear.com.
FAQs
Authgear SDK for Next.js 16 - OAuth authentication, session management, and JWT verification
The npm package @authgear/nextjs receives a total of 4 weekly downloads. As such, @authgear/nextjs popularity was classified as not popular.
We found that @authgear/nextjs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?

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.

Product
Socket Firewall blocks malicious VS Code and Open VSX extensions before install, protecting developers from compromised editor marketplaces.

Research
More than 140 Mastra npm packages were compromised in a supply chain attack that used a typosquatted dependency to deliver a cross-platform infostealer during installation.

Research
/Security News
A new npm package tests AI malware scanners with prompt injection, safety-triggering comments, context flooding, and obfuscated JavaScript.