authentication
Authentication
Quick Start
When working with authentication:
- Use
auth()from@/lib/authto get current session - Verify roles before admin operations
- Use middleware for route protection
- Never store tokens in localStorage (use httpOnly cookies)
- Validate JWT tokens in API routes
Key Files
auth.ts- NextAuth.js configurationsrc/lib/auth/- Auth utilitiesmiddleware.ts- Route protectionsrc/app/api/auth/- Auth API routes
Common Patterns
Get Current Session
import { auth } from '@/lib/auth';
export async function GET(request: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ user: session.user });
}
Check Admin Role
const session = await auth();
if (session?.user?.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
Protected API Route
import { auth } from '@/lib/auth';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
// 1. Check authentication
const session = await auth();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// 2. Check authorization (if needed)
if (session.user.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// 3. Process request
const body = await request.json();
// ... business logic
}
Middleware Protection
// middleware.ts
import { auth } from '@/lib/auth';
import { NextResponse } from 'next/server';
export async function middleware(request: NextRequest) {
const session = await auth();
// Protect admin routes
if (request.nextUrl.pathname.startsWith('/admin')) {
if (!session || session.user.role !== 'admin') {
return NextResponse.redirect(new URL('/login', request.url));
}
}
return NextResponse.next();
}
Sign In/Out
import { signIn, signOut } from '@/lib/auth';
// Sign in
await signIn('google', {
callbackUrl: '/dashboard',
});
// Sign out
await signOut({
callbackUrl: '/',
});
User Roles
admin- Full accesscustomer- Regular usermoderator- Limited admin access
Session Structure
interface Session {
user: {
id: string;
email: string;
name?: string;
role: 'admin' | 'customer' | 'moderator';
image?: string;
};
expires: string;
}
More from santiagoxor/pintureria-digital
checkout-payments
Specialized skill for working with checkout and payment systems including MercadoPago integration, order management, address validation, and checkout flow. Use when implementing checkout improvements, integrating payment methods, debugging payment issues, or optimizing checkout process.
39postgres-best-practices
Postgres performance optimization guidelines from Supabase. Contains rules across 8 categories prioritized by impact. Use when writing SQL queries, designing schemas, implementing indexes, optimizing queries, reviewing database performance, configuring connection pooling, or working with Row-Level Security (RLS).
29testing-qa
Specialized skill for writing and maintaining tests including unit tests, integration tests, E2E tests with Playwright, and accessibility tests. Use when writing tests for new features, debugging failed tests, improving test coverage, or setting up E2E tests.
18error-handling
Specialized skill for implementing proper error handling, logging, user-friendly error messages, and error recovery strategies. Use when implementing error handling in APIs, components, or when debugging error issues.
17lighthouse-audit
Specialized skill for running Lighthouse audits, analyzing Core Web Vitals, identifying performance opportunities, and generating performance reports. Use when auditing performance, analyzing Lighthouse metrics, optimizing Core Web Vitals, or generating performance reports.
17git-commit-push
Automates git commit and push workflow with descriptive commit messages. Analyzes changes, generates conventional commit messages, stages files, commits, and pushes to remote. Use when the user asks to commit changes, push code, or save work to git.
17