Next.js › API Routes
What are common performance and security pitfalls to avoid when building API routes at scale?
AdvancedAnswer
Common pitfalls include not validating incoming data which can lead to bad or malicious input, running slow database queries without caching, and not setting proper rate limits, which can let a single user overwhelm your server. Fixing these means validating input, caching where possible, and adding rate limiting for public endpoints.
import { z } from 'zod';
const schema = z.object({ email: z.string().email() });
export default function handler(req, res) {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ error: 'Invalid input' });
}
res.status(200).json({ ok: true });
}Real-world example A signup API route validates the submitted email format before creating an account, preventing malformed data from ever reaching the database and causing errors later.