@auth-gate/nextjs
v0.6.0
Published
Next.js SDK for [AuthGate](https://authgate.dev) — drop-in authentication with OAuth, email, SMS, and MFA for Next.js App Router.
Downloads
513
Readme
@auth-gate/nextjs
Next.js SDK for AuthGate — drop-in authentication with OAuth, email, SMS, and MFA for Next.js App Router.
Installation
npm install @auth-gate/nextjsQuick Start
1. Environment Variables
AUTHGATE_API_KEY=your_api_key
NEXT_PUBLIC_APP_URL=http://localhost:30002. Initialize the SDK
// lib/auth.ts
import { createAuthGate } from "@auth-gate/nextjs";
export const { client, handlers, session } = createAuthGate({
apiKey: process.env.AUTHGATE_API_KEY!,
baseUrl: "https://authgate.dev",
appUrl: process.env.NEXT_PUBLIC_APP_URL!,
});3. Create the Catch-All Route
// app/api/auth/[...authgate]/route.ts
import { handlers } from "@/lib/auth";
export const { GET, POST } = handlers;That's it — all auth routes are now available.
4. Read the Session
// app/dashboard/page.tsx
import { session } from "@/lib/auth";
import { redirect } from "next/navigation";
export default async function DashboardPage() {
const user = await session.getSession();
if (!user) redirect("/login");
return <p>Hello, {user.name}</p>;
}Route Map
The catch-all handler registers these routes under /api/auth/:
| Method | Route | Description |
|--------|-------|-------------|
| GET | /api/auth/[provider]/login | Start OAuth flow (google, github, discord, azure, apple) |
| GET | /api/auth/callback | OAuth / magic link callback |
| POST | /api/auth/email/signup | Email registration |
| POST | /api/auth/email/signin | Email sign-in |
| POST | /api/auth/email/forgot-password | Request password reset |
| POST | /api/auth/email/reset-password | Confirm password reset |
| POST | /api/auth/email/verify-code | Verify email with OTP |
| POST | /api/auth/magic-link/send | Send magic link |
| POST | /api/auth/sms/send-code | Send SMS code |
| POST | /api/auth/sms/verify-code | Verify SMS code |
| POST | /api/auth/mfa/verify | Complete MFA challenge |
| POST | /api/auth/refresh | Refresh session token |
| POST | /api/auth/logout | Sign out and revoke session |
| GET | /api/auth/me | Get current user |
Route Protection
Layout-Level (Recommended)
// app/dashboard/layout.tsx
import { session } from "@/lib/auth";
import { redirect } from "next/navigation";
export default async function DashboardLayout({ children }) {
const user = await session.getSession();
if (!user) redirect("/login");
return <>{children}</>;
}Middleware (Optional)
For protecting multiple route groups at the edge:
// middleware.ts
import { createAuthGateMiddleware } from "@auth-gate/nextjs";
import { client } from "@/lib/auth";
const authMiddleware = createAuthGateMiddleware(client, {
loginPath: "/login",
matcher: ["/dashboard/:path*", "/settings/:path*"],
});
export async function middleware(request) {
const response = await authMiddleware(request);
if (response) return response;
// ...other middleware
}
export const config = {
matcher: ["/dashboard/:path*", "/settings/:path*"],
};The middleware decrypts the session cookie at the edge and redirects unauthenticated users. It also periodically revalidates sessions (every 5 minutes) using the refresh token.
Session Helpers
import { session } from "@/lib/auth";
// Read the current user (server components, actions, route handlers)
const user = await session.getSession();
// Set a session (used internally by handlers)
await session.setSession(user);
// Clear the session
await session.clearSession();Sessions are AES-256-GCM encrypted cookies with a 7-day default TTL.
Authentication Examples
OAuth Sign-In
<a href="/api/auth/google/login">Sign in with Google</a>
<a href="/api/auth/github/login">Sign in with GitHub</a>Email Sign-In
const res = await fetch("/api/auth/email/signin", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (data.mfa_required) {
// Handle MFA challenge
const mfaRes = await fetch("/api/auth/mfa/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
mfa_challenge: data.mfa_challenge,
code: totpCode,
method: "totp",
}),
});
}SMS Sign-In
await fetch("/api/auth/sms/send-code", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone: "+15551234567" }),
});
await fetch("/api/auth/sms/verify-code", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone: "+15551234567", code: "123456" }),
});API Reference
createAuthGate(config)
Creates the SDK instance. Returns { client, handlers, session }.
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| apiKey | string | Yes | AuthGate API key (also used to resolve project ID) |
| baseUrl | string | Yes | AuthGate instance URL |
| appUrl | string | Yes | Your app's URL |
| cookieName | string | No | Cookie name (default: __authgate) |
| sessionMaxAge | number | No | Session TTL in seconds (default: 604800) |
| callbackPath | string | No | Callback path (default: /api/auth/callback) |
createAuthGateMiddleware(client, options?)
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| loginPath | string | "/login" | Redirect path for unauthenticated users |
| matcher | string[] | ["/dashboard/:path*"] | Route patterns to protect |
License
MIT
