This tutorial aims to provide a comprehensive introduction to API routes in Next.js. By the end of this guide, you will understand what API routes are, why they're important, and how to use them effectively in your Next.js applications.
You will learn:
- The concept of API routes
- The importance of API routes
- How to create API routes in Next.js
Prerequisites:
- Basic knowledge of JavaScript and React.js
- Familiarity with Node.js and Express.js could be helpful but is not mandatory
- Installed Node.js and npm on your local development machine
- Basic understanding of APIs
In Next.js, API routes provide a solution to build your API with Node.js, which makes it possible to have server-side code directly in your Next.js application. They can be deployed as serverless functions (also known as lambdas), which makes your app scalable.
In Next.js, API routes follow the file system based routing. To create an API route, you can create a file in the pages/api
directory, which will be treated as an API endpoint.
Each file in the pages/api
directory is mapped to /api/*
and becomes an API route. For example, if you create pages/api/user.js
, it will be accessible at http://localhost:3000/api/user
.
req
object to access the HTTP request details.res
object to send HTTP response.getServerSideProps
or getStaticProps
instead.Let's create a basic API route that sends a JSON response containing a message.
// File location: pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello Next.js' })
}
req
is an instance of http.IncomingMessage
, plus some additional functionality specific to Next.js.res
is an instance of http.ServerResponse
, plus some additional functionality specific to Next.js.http://localhost:3000/api/hello
.You can also handle different HTTP methods (like GET, POST) in your API route. Here's an example:
// File location: pages/api/user.js
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ name: 'John Doe' })
} else if (req.method === 'POST') {
// Process a POST request
} else {
res.setHeader('Allow', ['GET', 'POST'])
res.status(405).end(`Method ${req.method} Not Allowed`)
}
}
req.method
can be used to determine the HTTP method of the request. res.setHeader
and res.status().end()
are used to handle the unsupported methods.In this tutorial, we learned about API routes in Next.js, how to create them, and how to handle different HTTP methods. We also learned about the req
and res
objects that we use in the API route handler.
For further learning, you can explore more about middleware, error handling, and environment variables in Next.js API routes.
Additional resources:
- Next.js API routes documentation
- Next.js API middlewares
Solutions:
pages/api/myName.js
could look like this:javascript
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ name: 'Your Name' })
} else {
res.status(405).end(`Method ${req.method} Not Allowed`)
}
}
pages/api/products.js
could look like this:export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json(products)
} else {
res.status(405).end(Method ${req.method} Not Allowed
)
}
}
3. Your API route file `pages/api/echo.js` could look like this:
javascript
export default function handler(req, res) {
if (req.method === 'POST') {
res.status(200).json(req.body)
} else {
res.status(405).end(Method ${req.method} Not Allowed
)
}
}
``
Please note, to parse the incoming request body, you would need to use a middleware like
body-parseror inbuilt
express.json()` if you are using Express.js.