Defining API routes in Next.js
In the previous chapter, we used RSCs to access our database via a data layer; no API routes were needed for that! However, sometimes, it still makes sense to expose an external API. As an example, we might want to allow third-party apps to query blog posts. Thankfully, Next.js also has a feature to define API routes, called Route Handlers.
Route Handlers are also defined inside the src/app/
directory but in a route.js
file instead of a page.js
file (a path can only be either a route or a page, so only one of these files should be placed inside a folder). Instead of exporting a page component, we need to export functions that handle various types of requests there. For example, to handle a GET
request, we must define and export the following function:
export async function GET() {
Next.js supports the following HTTP methods for Route Handlers: GET
, POST
, PUT
, PATCH
, DELETE
, HEAD
, and OPTIONS
. For unsupported methods, Next.js will return a 405...