- Symptom
- The AI route answers requests that carry no session cookieAI provider usage grows much faster than your number of real users
- Cause
- Route Handlers are public HTTP endpoints that any client can call, not only your own pages. A handler that passes the request body to a paid model with your server key spends money on every call, whoever makes it.
- Fix
- Check the user's session at the top of the handler and return 401 without one, then apply a per-user or per-IP rate limit and return 429 when it is hit. Also turn on any rate limiting your host provides, and set a hard spend limit with the AI provider as a backstop.
- Apply
import { NextResponse } from 'next/server' import { auth } from '@/lib/auth' import { checkRateLimit } from '@/lib/rate-limit' export async function POST(request: Request) { const session = await auth() if (!session?.user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { rateLimited } = await checkRateLimit(request) if (rateLimited) { return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 }) } // call the model here }- Affected
- Next.js Route Handlers and Pages Router API Routes that call a paid AI API
- Sources
Last verified 2026-10-27 · Confirmed by 0 builders