Route handler allows us to define API endpoints with custom logic used to handle different HTTP request. Similar to how you can define webpages using page.jsx
, these API endpoints are created using route.js
.
What is an API endpoint
API stands for application programming interface, and it serves as a bridge, allowing the client to communicate with the server. The client sends an HTTP request to the API endpoint, and the endpoint processes the request and responds accordingly. Instead of rendering a webpage, the API endpoints returns data, structured data, usually in JSON format.
Next.js supports 7 different types of HTTP requests, GET
, POST
, PUT
, PATCH
, DELETE
, HEAD
, and OPTIONS
. Each of them serves a specific purpose:
GET
: Retrieves data from server.POST
: Adds new data to the server.PUT
: Updates existing data, such as updating a blog post with new content.PATCH
: Updates part of existing data, such as updating the title of the blog post.DELETE
: Removes data from server.HEAD
: Retrieves the metadata of a resource, without transmitting the resource itself.OPTIONS
: Returns the allowed HTTP methods for a specific API endpoint.
Creating an API route handler
To define an API endpoint using Next.js, create a route.js
file like this:
1app
2├── api
3│ └── users
4│ └── route.js <===== Endpoint: /api/users
5├── blog
6├── dashboard
7├── favicon.ico
8├── fonts
9├── globals.css
10├── layout.jsx
11└── page.jsx
It is customary to design your API endpoints so that they all start with /api
. Of course, you can choose to not follow this custom, but note that you must design your routes carefully so that your API endpoints do not conflict with the regular page routes.
It is not allowed to have both page.jsx
and route.js
under the same directory.