@gablura/auth-next
Production-ready Next.js authentication with NextAuth.js.
@gablura/auth-next
Production-ready Next.js authentication with NextAuth.js. Drop-in auth with credentials, Google OAuth, 2FA, email verification, and password reset.
Why it exists
NextAuth handles session management and OAuth. This package adds what NextAuth does not provide out of the box:
| Feature | NextAuth alone | With @gablura/auth-next |
|---|---|---|
| HMAC token exchange to backend | Manual | Built-in |
| Silent token refresh with dedup | Manual | Built-in |
| 2FA (TOTP) | Requires third-party adapter | Built-in |
| Email verification | Manual | API handler + UI |
| Password reset | Manual | API handler + UI |
| Rate limiting on auth routes | Manual | Built-in |
| Pre-built login/register UI | Build yourself | Drop-in components |
| Custom UI hooks | N/A | useAuthForm, etc. |
| Account lockout | Manual | Via backend |
| Session binding (fingerprint) | Manual | Via backend |
Features
- NextAuth.js with JWT strategy
- Credentials + Google OAuth providers
- 2FA (TOTP) for both credential and OAuth logins
- Email verification with token-based flow
- Password reset with email delivery
- Token exchange — HMAC-signed proof to backend
- Silent refresh — Automatic token renewal
- Pre-built UI components — Login, register, forgot/reset password, email verification
- React hooks — Build your own custom UI with form logic
- API route handlers — Ready-to-use Next.js route handlers
- ORM-agnostic — Works with Prisma, Drizzle, MongoDB, or any custom backend
Next.js Compatibility
| Next.js Version | Status |
|---|---|
| v14.x | Supported |
| v15.x | Supported |
| v16.x | Supported (requires next-auth@4.24.14+) |
Two ways to use
Option A: Pre-built Components
import { AuthPage, ForgotPasswordPage, ResetPasswordPage, VerifyEmailPage } from "@gablura/auth-next/components";
// Full auth UI with zero custom code
Option B: Custom UI (Hooks)
"use client";
import { useAuthForm } from "@gablura/auth-next/hooks";
export default function MyLogin() {
const { register, handleSubmit, errors, isSubmitting, onSubmit, handleGoogle } = useAuthForm({
mode: "login",
callbackUrl: "/dashboard",
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} placeholder="Email" />
<input {...register("password")} type="password" placeholder="Password" />
<button type="submit" disabled={isSubmitting}>Sign in</button>
<button type="button" onClick={handleGoogle}>Google</button>
</form>
);
}
Installation
Install
npm install @gablura/auth-next next-auth
Peer dependencies
| Package | Version | Required |
|---|---|---|
next-auth | >= 4.24.14 | Yes |
next | 14 - 16 | Yes |
Environment variables
AUTH_SECRET=your-shared-secret-with-backend
NEXTAUTH_SECRET=your-nextauth-jwt-secret
NEXTAUTH_URL=https://your-app.com
BACKEND_URL=http://localhost:5000
# Google OAuth (optional)
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
# Email
EMAIL_SERVER_HOST=smtp.example.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=...
EMAIL_SERVER_PASSWORD=...
EMAIL_FROM=noreply@example.com
Quick Start
1. Create API route
// app/api/auth/[...nextauth]/route.ts
import { createAuthOptions } from "@gablura/auth-next";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
const authOptions = await createAuthOptions({
hmacSecret: process.env.AUTH_SECRET!,
nextAuthSecret: process.env.NEXTAUTH_SECRET,
backendUrl: process.env.BACKEND_URL,
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
adapter: PrismaAdapter(prisma),
dataStore: {
findUserByEmail: (email) => prisma.user.findUnique({ where: { email } }),
createUser: (data) => prisma.user.create({ data }),
updateUserByEmail: (email, data) => prisma.user.update({ where: { email }, data }),
createVerificationToken: (data) => prisma.verificationToken.create({ data }),
findVerificationToken: (token) => prisma.verificationToken.findUnique({ where: { token } }),
deleteVerificationToken: (token, identifier) =>
prisma.verificationToken.delete({ where: { token_identifier: { token, identifier } } }),
createPasswordResetToken: (data) => prisma.passwordResetToken.create({ data }),
findPasswordResetToken: (token) => prisma.passwordResetToken.findFirst({ where: { token, expires: { gt: new Date() } } }),
deletePasswordResetToken: (email) => prisma.passwordResetToken.delete({ where: { email } }),
},
userStore: {
findByEmail: (email) => prisma.user.findUnique({ where: { email } }),
findById: (id) => prisma.user.findUnique({ where: { id } }),
update: (id, data) => prisma.user.update({ where: { id }, data }),
},
pages: {
signIn: "/auth/login",
error: "/auth/error",
},
});
export const GET = authOptions.handlers.GET;
export const POST = authOptions.handlers.POST;
2. Add auth pages
// app/auth/login/page.tsx
import { AuthPage } from "@gablura/auth-next/components";
export default function Login() {
return <AuthPage callbackUrl="/dashboard" />;
}
3. Set up proxy (Next.js 16+)
// proxy.ts (Next.js 16+)
import { withAuth } from "next-auth/middleware";
export default withAuth({
pages: { signIn: "/auth/login" },
});
export const config = {
matcher: ["/dashboard/:path*", "/settings/:path*"],
};
Configuration
AuthNextConfig
interface AuthNextConfig {
backendUrl?: string; // Backend URL (default: env.BACKEND_URL)
hmacSecret: string; // Required — shared with backend
nextAuthSecret?: string; // Optional — defaults to hmacSecret
google?: {
clientId: string;
clientSecret: string;
};
pages?: {
signIn?: string;
error?: string;
};
adapter?: unknown; // PrismaAdapter, DrizzleAdapter, etc.
dataStore: DataStore; // Required — database operations
userStore: {
findByEmail(email: string): Promise<User | null>;
findById(id: string): Promise<User | null>;
update?(id: string, data: Record<string, unknown>): Promise<void>;
};
callbackRoutes?: {
success?: string; // After login (default: "/authentication/success")
login?: string; // Sign-in page
register?: string; // Register page
twoFactor?: string; // 2FA page
verifyEmail?: string; // After email verified
verifyEmailPage?: string; // Verify-email page in emails
forgotPassword?: string; // Forgot password
resetPassword?: string; // Reset password
error?: string; // Error page
};
sessionMaxAge?: number; // Default: 7 days (seconds)
sessionUpdateAge?: number; // Default: 24 hours (seconds)
}
DataStore
The dataStore is required and makes the package ORM-agnostic:
interface DataStore {
findUserByEmail(email: string): Promise<User | null>;
createUser(data: { name?: string; email: string; password?: string }): Promise<{ id: string }>;
updateUserByEmail(email: string, data: Record<string, unknown>): Promise<void>;
createVerificationToken(data: { identifier: string; token: string; expires: Date }): Promise<void>;
findVerificationToken(token: string): Promise<{ identifier: string; expires: Date } | null>;
deleteVerificationToken(token: string, identifier: string): Promise<void>;
createPasswordResetToken(data: { email: string; token: string; expires: Date }): Promise<void>;
findPasswordResetToken(token: string): Promise<{ email: string; token: string } | null>;
deletePasswordResetToken(email: string): Promise<void>;
}
Usage
Pre-built Components
All components are imported from @gablura/auth-next/components.
AuthPage
Full-screen login/register page with toggle.
import { AuthPage } from "@gablura/auth-next/components";
<AuthPage callbackUrl="/dashboard" />
ForgotPasswordPage
import { ForgotPasswordPage } from "@gablura/auth-next/components";
<ForgotPasswordPage />
ResetPasswordPage
import { ResetPasswordPage } from "@gablura/auth-next/components";
<ResetPasswordPage token={searchParams.get("token")} />
VerifyEmailPage
import { VerifyEmailPage } from "@gablura/auth-next/components";
<VerifyEmailPage token={searchParams.get("token")} />
Hooks
All hooks are imported from @gablura/auth-next/hooks.
useAuthForm
"use client";
import { useAuthForm } from "@gablura/auth-next/hooks";
function MyForm() {
const {
register,
handleSubmit,
errors,
isSubmitting,
onSubmit,
handleGoogle,
formError,
clearFormError,
} = useAuthForm({
mode: "login",
callbackUrl: "/dashboard",
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} />
{errors.email && <span>{errors.email.message}</span>}
<input {...register("password")} type="password" />
<button type="submit" disabled={isSubmitting}>Sign in</button>
<button type="button" onClick={handleGoogle}>Google</button>
</form>
);
}
useForgetPasswordPage
const { error, success, register, handleSubmit, errors, isSubmitting, onSubmit } = useForgetPasswordPage();
useResetPasswordPage
const { error, success, register, handleSubmit, errors, isSubmitting, onSubmit } = useResetPasswordPage({ token });
useVerifyEmail
const { status, message } = useVerifyEmail({ token });
API Route Handlers
All handlers are imported from @gablura/auth-next/api.
| Handler | Purpose |
|---|---|
handleRegister | User registration |
handleForgotPassword | Send reset email |
handleResetPassword | Reset password with token |
handleVerifyEmail | Verify email with token |
Email Functions
import { sendVerificationEmail, sendPasswordResetEmail } from "@gablura/auth-next/email";
License
MIT License
Copyright 2026 Gablura
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.