#Route Handlers
1 messages · Page 1 of 1 (latest)
Hi @lunar dagger. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. They are defined in a route.js|ts file inside the app directory and can be nested inside the app directory, similar to page.js and layout.js. However, there cannot be a route.js file at the same route segment level as page.js.
If you need to fetch data in a client component, you can call a Route Handler from the client. Route Handlers execute on the server and return the data to the client. This is useful when you don't want to expose sensitive information to the client, such as API tokens.
Here's an example of how to define a Route Handler:
// app/api/route.ts
export async function GET(request: Request) {}
The following HTTP methods are supported: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS. If an unsupported method is called, Next.js will return a 405 Method Not Allowed response.
In addition to supporting native Request and Response, Next.js extends them with NextRequest and NextResponse to provide convenient helpers for advanced use cases.
For more information, you can refer to the Route Handlers documentation (https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and the API reference for the route.js special file (https://nextjs.org/docs/app/api-reference/file-conventions/route).
Please note that Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Route Handlers together.
Sources:
- Next.js Documentation: Route Handlers (https://nextjs.org/docs/app/building-your-application/routing/route-handlers)
- Next.js Blog: Next.js 13.2 (https://nextjs.org/blog/next-13-2)
- Next.js Documentation: Data Fetching, Caching, and Revalidating (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@lunar dagger kapa.ai is still learning and improving, please let us know how it did by reacting below