In this tutorial, we will learn how to create your first API endpoint in Next.js. API endpoints are paths or URLs where API (Application Programming Interface) can be accessed by clients over HTTP.
By the end of this tutorial, you will be able to:
- Understand the basics of creating an API endpoint in Next.js
- Handle incoming HTTP requests and send responses
Prerequisites:
- Basic knowledge of JavaScript and Node.js
- Next.js installed on your local machine
Next.js provides an integrated server-side solution, allowing us to create API routes in our Next.js app. These routes are server-side and do not add to your client-side JavaScript bundle size.
To create an API route, we create a file in the pages/api
directory. The filename will be the API endpoint.
pages/api
directory. The name of the file will be the API endpoint. For example, hello.js
will be accessed at http://localhost:3000/api/hello
.req
: An instance of http.IncomingMessage, plus some pre-built middlewaresres
: An instance of http.ServerResponse, plus some helper functionsHere is a simple example of an API endpoint that returns a JSON response:
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ text: 'Hello' })
}
export default function handler(req, res) { ... }
: This creates an API route function. The function accepts two arguments: a request (req
) and a response (res
).res.status(200).json({ text: 'Hello' })
: This sends a response with a status code of 200 (OK) and the JSON response { text: 'Hello' }
.You can access this API endpoint at http://localhost:3000/api/hello
.
In this tutorial, we have:
- Learned how to create an API endpoint in Next.js
- Learned how to handle requests and send responses from an API endpoint
Next steps:
- Learn how to connect to a database in your Next.js API routes
- Learn how to use middlewares in your API routes
Additional resources:
- Next.js API routes documentation
/api/goodbye
that sends a JSON response { text: 'Goodbye' }
./api/user
that sends a JSON response { name: 'John Doe', email: 'john.doe@example.com' }
.Solutions:
1.
// pages/api/goodbye.js
export default function handler(req, res) {
res.status(200).json({ text: 'Goodbye' })
}
// pages/api/user.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe', email: 'john.doe@example.com' })
}
Tips:
- Experiment with different response status codes and see how your API behaves.
- Try creating an API route that accepts query parameters.