Modern authentication with Auth.js (NextAuth v5) including providers, callbacks, and session management.
# Auth.js v5 Implementation for Google Antigravity
Auth.js (NextAuth v5) provides a complete authentication solution for Next.js applications. Google Antigravity's Gemini 3 helps you implement secure auth flows with OAuth providers, credentials, and session management.
## Auth Configuration
Set up Auth.js with providers and callbacks:
```typescript
// auth.ts
import NextAuth from "next-auth";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
import Credentials from "next-auth/providers/credentials";
import { db } from "@/db";
import { users, accounts, sessions, verificationTokens } from "@/db/schema";
import { eq } from "drizzle-orm";
import bcrypt from "bcryptjs";
import { z } from "zod";
const credentialsSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: DrizzleAdapter(db, {
usersTable: users,
accountsTable: accounts,
sessionsTable: sessions,
verificationTokensTable: verificationTokens,
}),
session: {
strategy: "jwt",
},
pages: {
signIn: "/login",
error: "/auth/error",
},
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
GitHub({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
Credentials({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const parsed = credentialsSchema.safeParse(credentials);
if (!parsed.success) return null;
const { email, password } = parsed.data;
const user = await db.query.users.findFirst({
where: eq(users.email, email),
});
if (!user || !user.hashedPassword) return null;
const isValid = await bcrypt.compare(password, user.hashedPassword);
if (!isValid) return null;
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
};
},
}),
],
callbacks: {
async jwt({ token, user, trigger, session }) {
if (user) {
token.id = user.id;
token.role = user.role;
}
if (trigger === "update" && session) {
token.name = session.name;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user.id = token.id as string;
session.user.role = token.role as string;
}
return session;
},
async signIn({ user, account, profile }) {
if (account?.provider === "google") {
const email = user.email;
if (email && !email.endsWith("@company.com")) {
return false;
}
}
return true;
},
},
events: {
async signIn({ user, account, isNewUser }) {
if (isNewUser) {
console.log(`New user signed up: ${user.email}`);
}
},
async signOut({ token }) {
console.log(`User signed out: ${token?.email}`);
},
},
});
```
## Type Extensions
Extend NextAuth types for custom fields:
```typescript
// types/next-auth.d.ts
import { DefaultSession, DefaultUser } from "next-auth";
import { JWT, DefaultJWT } from "next-auth/jwt";
declare module "next-auth" {
interface Session {
user: {
id: string;
role: string;
} & DefaultSession["user"];
}
interface User extends DefaultUser {
role: string;
}
}
declare module "next-auth/jwt" {
interface JWT extends DefaultJWT {
id: string;
role: string;
}
}
```
## API Route Handler
Set up the auth API routes:
```typescript
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
```
## Middleware Protection
Protect routes with middleware:
```typescript
// middleware.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
const publicRoutes = ["/", "/login", "/signup", "/about"];
const authRoutes = ["/login", "/signup"];
const adminRoutes = ["/admin"];
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isAdmin = req.auth?.user?.role === "admin";
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const isAdminRoute = adminRoutes.some((route) =>
nextUrl.pathname.startsWith(route)
);
if (isAuthRoute && isLoggedIn) {
return NextResponse.redirect(new URL("/dashboard", nextUrl));
}
if (isAdminRoute && !isAdmin) {
return NextResponse.redirect(new URL("/", nextUrl));
}
if (!isPublicRoute && !isLoggedIn) {
const callbackUrl = encodeURIComponent(nextUrl.pathname);
return NextResponse.redirect(
new URL(`/login?callbackUrl=${callbackUrl}`, nextUrl)
);
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
```
## Server Actions for Auth
Implement auth actions:
```typescript
// app/actions/auth.ts
"use server";
import { signIn, signOut } from "@/auth";
import { AuthError } from "next-auth";
import bcrypt from "bcryptjs";
import { db } from "@/db";
import { users } from "@/db/schema";
import { eq } from "drizzle-orm";
export async function signInWithGoogle() {
await signIn("google", { redirectTo: "/dashboard" });
}
export async function signInWithGitHub() {
await signIn("github", { redirectTo: "/dashboard" });
}
export async function signInWithCredentials(formData: FormData) {
const email = formData.get("email") as string;
const password = formData.get("password") as string;
try {
await signIn("credentials", {
email,
password,
redirectTo: "/dashboard",
});
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case "CredentialsSignin":
return { error: "Invalid credentials" };
default:
return { error: "Something went wrong" };
}
}
throw error;
}
}
export async function register(formData: FormData) {
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const name = formData.get("name") as string;
const existingUser = await db.query.users.findFirst({
where: eq(users.email, email),
});
if (existingUser) {
return { error: "User already exists" };
}
const hashedPassword = await bcrypt.hash(password, 12);
await db.insert(users).values({
email,
name,
hashedPassword,
role: "user",
});
await signIn("credentials", {
email,
password,
redirectTo: "/dashboard",
});
}
export async function logout() {
await signOut({ redirectTo: "/" });
}
```
## Login Form Component
Build a complete login form:
```typescript
// components/LoginForm.tsx
"use client";
import { useFormState, useFormStatus } from "react-dom";
import { signInWithCredentials, signInWithGoogle, signInWithGitHub } from "@/app/actions/auth";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button
type="submit"
disabled={pending}
className="w-full py-2 bg-primary-600 text-white rounded-lg"
>
{pending ? "Signing in..." : "Sign In"}
</button>
);
}
export function LoginForm() {
const [state, formAction] = useFormState(signInWithCredentials, null);
return (
<div className="max-w-md mx-auto space-y-6">
<form action={formAction} className="space-y-4">
{state?.error && (
<div className="p-3 bg-red-100 text-red-700 rounded">
{state.error}
</div>
)}
<input
name="email"
type="email"
placeholder="Email"
required
className="w-full px-3 py-2 border rounded-lg"
/>
<input
name="password"
type="password"
placeholder="Password"
required
className="w-full px-3 py-2 border rounded-lg"
/>
<SubmitButton />
</form>
<div className="flex gap-2">
<form action={signInWithGoogle} className="flex-1">
<button type="submit" className="w-full py-2 border rounded-lg">
Google
</button>
</form>
<form action={signInWithGitHub} className="flex-1">
<button type="submit" className="w-full py-2 border rounded-lg">
GitHub
</button>
</form>
</div>
</div>
);
}
```
## Best Practices
1. **Use JWT strategy for API routes** - Better for serverless environments
2. **Extend types properly** - Add custom fields to session and token
3. **Implement proper callbacks** - Handle sign-in logic and session data
4. **Protect routes with middleware** - Single point of access control
5. **Hash passwords securely** - Use bcrypt with proper salt rounds
Auth.js with Google Antigravity enables secure, flexible authentication with intelligent provider configuration.This auth prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their auth implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For auth projects, consider mentioning your framework version, coding style, and any specific libraries you're using.