What are common performance and security pitfalls to avoid when building API routes at scale?
Short answer
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.
Advertisement
AModel answer
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.
Likely follow-ups
- What library is commonly used for validating request bodies in Next.js?
- How would you add rate limiting to a public API route?
Related topics