# Route Handlers (APIs)

> Building REST APIs and webhooks using route.ts.

Subject: Next.js | Lesson 44 of 65 | 4 min read
Interactive lesson: https://codewithanimation.in/nextjs/route-handlers
Previous: [Breadcrumbs](https://codewithanimation.in/nextjs/use-selected-layout-segments.md) | Next: [Static vs Dynamic Handlers](https://codewithanimation.in/nextjs/static-vs-dynamic-handlers.md)

## Building APIs

Route Handlers allow you to create custom request handlers for a given route using the standard Web `Request` and `Response` APIs.

They are defined in a `route.js` or `route.ts` file.

## Server-Side Endpoints

While Server Actions are great for mutations, sometimes you need a traditional API endpoint.

Route Handlers are perfect for webhooks (like receiving a Stripe payment success event), external API access, or standard REST endpoints.

## HTTP Methods

You create endpoints by exporting functions named after HTTP methods.

Supported methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, and `OPTIONS`.

Example: `export async function GET(request) { return Response.json({ data: 'hello' }); }`

## Common mistake: The Route Conflict Trap

A very common mistake is placing a `route.ts` file and a `page.tsx` file in the exact same folder.

This causes a build error because Next.js doesn't know which file should handle an incoming `GET` request to that path.

Usually, developers put their route handlers inside an `/api/` folder to prevent this collision.

## Tip: Caching

`GET` handlers are automatically cached (statically evaluated) during the build process if they don't use dynamic functions (like reading cookies or headers).

`POST`, `PUT`, and `DELETE` handlers are never cached.

## Try it: The REST Client

Use the mock REST client below to send different HTTP requests to the `/api/users` route handler. Watch how the correct exported function is triggered.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/nextjs/route-handlers

## Check yourself

### Question 1

What happens if you have both `/app/shop/page.tsx` and `/app/shop/route.ts`?

- A. The `page.tsx` takes priority.
- B. The app will throw a build error.
- C. The `route.ts` handles POSTs, and `page.tsx` handles GETs.
- D. It creates an API at `/shop/api` automatically.

Correct answer: B

Next.js throws a conflict error because both files are attempting to handle the same HTTP GET request to the `/shop` route.

- Why not A: Next.js does not prioritize one over the other.
- Why not C: Both attempt to handle GET requests, causing a conflict.
- Why not D: You must explicitly create an `/api` folder.

## Remember this

- Route Handlers are defined in a `route.ts` file.
- They export HTTP methods like `GET`, `POST`, and `DELETE`.
- They use the standard Web `Request` and `Response` APIs.
- You cannot have a `route.ts` and `page.tsx` in the exact same folder.
