Skip to content

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.


Folder Structure

API routes in CodeNearby live inside:

app/
└── api/
    └── your-endpoint/
        └── route.ts

Each folder under api/ maps to a RESTful endpoint.


Basic Template

To add a new API endpoint at /api/example, follow these steps:

  1. Create the folder:

    mkdir -p app/api/example
  2. 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 });
    }

Test It

Once added, you can test it by running the dev server:

npm run dev

Then visit:

http://localhost:3000/api/example

Or test with curl:

curl http://localhost:3000/api/example

Best Practices

  • Always return NextResponse from handlers.
  • Validate inputs using zod or 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).

Advanced: Dynamic Params

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 });
}

Example Use Cases

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

Commit & PR

Once tested:

Commit and create a Pull Request with a clear description:

feat(api): add /example route for demo purposes

Clone this wiki locally