Implementing API Keys for Your SaaS: Generation, Hashing, and Validation in Next.js
Why Your SaaS Needs API Keys Not every user wants OAuth. Developers building integrations need API keys: programmatic access, CI/CD pipelines, scripts, third-party apps. Here's how to implement a s...

Source: DEV Community
Why Your SaaS Needs API Keys Not every user wants OAuth. Developers building integrations need API keys: programmatic access, CI/CD pipelines, scripts, third-party apps. Here's how to implement a secure, production-ready API key system in Next.js. The Data Model model ApiKey { id String @id @default(cuid()) userId String user User @relation(fields: [userId], references: [id]) name String // 'Production', 'CI/CD', etc. keyHash String @unique // bcrypt hash of the key keyPrefix String // First 8 chars for display: 'sk_live_abc12345' lastUsedAt DateTime? createdAt DateTime @default(now()) expiresAt DateTime? revokedAt DateTime? @@index([userId]) } Generating a Secure Key import crypto from 'crypto' import bcrypt from 'bcryptjs' function generateApiKey(): { raw: string; hash: string; prefix: string } { // 32 random bytes = 256-bit key const rawKey = `sk_live_${crypto.randomBytes(32).toString('hex')}` const prefix = rawKey.slice(0, 16) // 'sk_live_' + 8 hex chars const hash = bcrypt.hashSyn