Next.js
Last updated at 2023-10-25

PUT Endpoint in Next.js API Router with TypeScript

ClickUp
Note
AI Status
Full
Last Edit By
Last edited time
Oct 25, 2023 07:48 AM
Metatag
Slug
put-endpoint-nextjs-api
Writer
Published
Published
Date
Oct 25, 2023
Category
Next.js
Next.js is a popular framework for building server-side rendered React applications.
It provides an API routing system that allows you to define serverless functions to handle HTTP requests.
In this article, we will look at how to handle PUT requests in Next.js API Router using TypeScript.

Prerequisites

Before we dive into the details, make sure you have the following prerequisites:
  • Basic knowledge of Next.js and React.
  • Familiarity with TypeScript.
  • Node.js and npm installed on your development machine.

Setting Up a Next.js Project

To get started, let's set up a new Next.js project.
Open your terminal and run the following commands:
npx create-next-app my-app cd my-app
This will create a new Next.js project and navigate you into its directory.
Next, let's create an API route to handle PUT requests.

Creating a PUT API Route

In Next.js, API routes are defined in the pages/api directory.
Let's create a new file called updateUser.ts inside the pages/api directory with the following code:
import { NextApiRequest, NextApiResponse } from 'next'; export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'PUT') { // Handle PUT request logic here res.status(200).json({ message: 'User updated successfully' }); } else { res.status(405).json({ message: 'Method Not Allowed' }); } }
In this code, we define a default export function that takes in the req (request) and res (response) objects from Next.js API Router.
We check if the request method is PUT and handle the PUT request logic accordingly.
If the request method is not PUT, we respond with a "Method Not Allowed" status.

Testing the PUT API Route

To test our PUT API route, we can use a tool like cURL or Postman.
Let's use cURL in this example. Open your terminal and run the following command:
curl -X PUT http://localhost:3000/api/updateUser
You should see a response with the message "User updated successfully" and a 200 status code.

Handling Request Body

In many cases, you will need to access the request body when handling a PUT request.
Next.js API Router allows you to parse the request body using the req.body property.
However, by default, Next.js does not parse the request body for API routes.
To enable request body parsing, we need to install and configure the body-parser middleware.
First, let's install the body-parser package by running the following command:
npm install body-parser
Next, let's update our updateUser.ts file with the following code:
import { NextApiRequest, NextApiResponse } from 'next'; import bodyParser from 'body-parser'; export const config = { api: { bodyParser: false, }, }; const jsonParser = bodyParser.json(); export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'PUT') { jsonParser(req, res, () => { const { userId, name } = req.body; // Handle PUT request logic here res.status(200).json({ message: `User ${userId} updated successfully` }); }); } else { res.status(405).json({ message: 'Method Not Allowed' }); } }
In this code, we import the body-parser package and configure Next.js API Router to disable the default request body parsing.
We then create a jsonParser middleware using bodyParser.json().
Inside the PUT request handling logic, we use the jsonParser middleware to parse the request body and access the userId and name properties.

Conclusion

In this article, we learned how to handle PUT requests in Next.js API Router using TypeScript.
We covered setting up a Next.js project, creating a PUT API route, testing the API route using cURL, and handling the request body.
We hope this article helps you in your Next.js development journey.

References

Feel free to refer to the official documentation and other resources for more detailed information on the topics covered in this article.

Discussion (0)

Related Posts