Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan

It's incredibly easy to build an API route in Next.js. You export a POST function, connect to MongoDB, and insert data. But it's equally easy to leave that endpoint wide open to abuse, bot spam, and malicious payloads.
Whenever I expose a public API endpoint (like a comment submission form or a contact form), I implement three non-negotiable layers of security.
If you don't rate-limit your public endpoints, a single script can insert 10,000 garbage comments into your MongoDB database in seconds.
While you can implement this in middleware using Redis (like Upstash), for smaller apps, I often use a lightweight in-memory cache mapped to IP addresses. If an IP exceeds 5 requests per minute, the API immediately returns a 429 Too Many Requests status.
Never trust client data. Even if your frontend has validation, a malicious user can bypass it by hitting your endpoint directly via curl or Postman.
I use Zod to rigorously validate every incoming payload.
typescriptimport { z } from 'zod';
const CommentSchema = z.object({
name: z.string().min(2).max(50),
text: z.string().min(5).max(1000),
blogId: z.string().length(24) // MongoDB ObjectId length
});
export async function POST(req: Request) {
const body = await req.json();
const result = CommentSchema.safeParse(body);
if (!result.success) {
return NextResponse.json({ error: "Invalid payload" }, { status: 400 });
}
// Proceed with safe, typed data
}
name field to crash the server, Zod catches it instantly.Automated bots crawl the web looking for unprotected forms to spam links. To prevent this, I integrate Cloudflare Turnstile or Google reCAPTCHA. The client must solve the challenge and send the token to the API route, which then verifies the token with the provider's servers before touching the database.
Implementing these three layers takes an extra 20 minutes, but it saves hours of cleaning up database spam down the line.