zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time π.
Made with by Zahid
views
zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time π.
Made with by Zahid
views

Share
Don't leave your API endpoints exposed. Implementation guide for secure authentication checks and preventing abuse.
Exposing API routes in Next.js is easy. Securing them takes intention. Without safeguards, your API is vulnerable to abuse, scraping, and unauthorized data access.
I noticed my public API was receiving thousands of requests from a single IP, causing my database costs to spike. I realized I had no protection against bots or spam.
Using a helper function to guard API routes.
1// lib/auth.ts
2import { auth } from "@clerk/nextjs";
3
4export function requireAuth() {
5 const { userId } = auth();
6 if (!userId) {
7 throw new Error("Unauthorized");
8 }
9 return userId;
10}1import { Ratelimit } from "@upstash/ratelimit";
2import { Redis } from "@upstash/redis";
3import { NextResponse } from "next/server";
4
5const ratelimit = new Ratelimit({
6 redis: Redis.fromEnv(),
7 limiter: Ratelimit.slidingWindow(10, "10 s"), // 10 requests per 10s
8});
9
10export async function POST(req: Request) {
11 const ip = req.headers.get("x-forwarded-for") ?? "127.0.0.1";
12
13 const { success } = await ratelimit.limit(ip);
14
15 if (!success) {
16 return NextResponse.json({ error: "Too many requests" }, { status: 429 });
17 }
18
19 // Proceed with logic...
20}Security is layers. Rate limiting stops the bots, and strict auth checks stop the hackers.
Tech Stack: Next.js, Upstash Redis, Clerk