-
-
Notifications
You must be signed in to change notification settings - Fork 22
How to Add a New API Route
Subhadip Saha edited this page May 15, 2025
·
1 revision
This guide helps contributors add new API routes to CodeNearby using Next.js 14’s App Router with the route.ts convention.
API routes in CodeNearby live inside:
app/
└── api/
└── your-endpoint/
└── route.ts
Each folder under api/ maps to a RESTful endpoint.
To add a new API endpoint at /api/example, follow these steps:
-
Create the folder:
mkdir -p app/api/example
-
Create the route handler:
// app/api/example/route.ts import { NextResponse } from 'next/server'; export async function GET(req: Request) { return NextResponse.json({ message: 'Hello from /api/example' }); } export async function POST(req: Request) { const body = await req.json(); // handle logic here return NextResponse.json({ received: body }); }
Once added, you can test it by running the dev server:
npm run devThen visit:
http://localhost:3000/api/example
Or test with curl:
curl http://localhost:3000/api/example- Always return
NextResponsefrom handlers. - Validate inputs using
zodor manual checks. - Avoid writing DB logic directly — use helpers from
lib/. - Respect rate limits or use caching if it’s read-heavy.
- Create subfolders if your route has nested operations (e.g.
api/gathering/[slug]/chat).
For dynamic routes like /api/user/[id], use:
// app/api/user/[id]/route.ts
export async function GET(
req: Request,
{ params }: { params: { id: string } }
) {
const { id } = params;
return NextResponse.json({ userId: id });
}| Route | Purpose |
|---|---|
/api/devs |
Search devs by skill/location |
/api/friends/request/[id] |
Send a friend request |
/api/posts/[id]/comments |
Handle nested post logic |
Once tested:
Commit and create a Pull Request with a clear description:
feat(api): add /example route for demo purposes