When building web applications with Next.js, you often need to handle various HTTP methods, including DELETE requests, to manage and manipulate data on the server.
In this article, we'll explore how to handle DELETE requests using Next.js API Routes with TypeScript.
What are Next.js API Routes?
Next.js API Routes provide a straightforward way to create API endpoints in your Next.js application.
These endpoints allow you to handle various HTTP methods like GET, POST, PUT, and DELETE, making it easy to build robust APIs for your frontend application.
Setting Up Next.js API Routes with TypeScript
Before we dive into handling DELETE requests, let's set up a basic Next.js API Route using TypeScript.
- Create a new directory called
pages
in your Next.js project if it doesn't already exist.
- Inside the
pages
directory, create a new file namedapi
(or any name you prefer) with the.ts
extension. For example,delete.ts
.
- In the
delete.ts
file, you can create your DELETE API endpoint:
// pages/api/delete.ts import { NextApiRequest, NextApiResponse } from 'next'; export default function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method === 'DELETE') { // Handle the DELETE request here res.status(200).json({ message: 'DELETE request handled successfully' }); } else { res.status(405).json({ message: 'Only DELETE requests are allowed' }); } }
In this example, we've created a basic API endpoint that handles DELETE requests.
It responds with a success message if the request method is DELETE; otherwise, it returns a 405 Method Not Allowed status.
Handling DELETE Requests with TypeScript
Now, let's implement the logic to handle DELETE requests in your TypeScript-based API route. You can use this route to delete data or perform any other action that requires a DELETE request.
Here's an example of how to delete an item using a DELETE request:
// pages/api/delete.ts import { NextApiRequest, NextApiResponse } from 'next'; export default function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method === 'DELETE') { const { id } = req.body; // const deletedItem = deleteItemById(id); // you can make database operation here const deletedItem = true if (deletedItem) { res.status(200).json({ message: 'Item deleted successfully' }); } else { res.status(404).json({ message: 'Item not found' }); } } else { res.status(405).json({ message: 'Only DELETE requests are allowed' }); } }
In this updated example:
- We extract the
id
of the item to delete from the request body. You can customize this based on your data structure.
- We perform the deletion operation, such as deleting the item from a database or a data store. Replace the
deleteItemById
function with your own logic to handle deletions.
- If the item is successfully deleted, we respond with a 200 OK status and a success message. If the item is not found, we return a 404 Not Found status.
Test DELETE API using curl
We can test the DELETE API using the
curl
command like below:curl -X DELETE -H "Content-Type: application/json" -d '{"id": 123}' http://localhost:3000/api/delete
Sending DELETE Requests using fetch
To test your DELETE API endpoint, you can use tools like
fetch
in JavaScript or any API client of your choice. Here's an example of how to send a DELETE request using fetch
with TypeScript:const itemIdToDelete = 123; // Replace with the ID of the item you want to delete fetch('/api/delete', { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ id: itemIdToDelete }), }) .then(async (response) => { if (response.ok) { const data = await response.json(); console.log(data.message); } else { const errorData = await response.json(); console.error('Error:', errorData.message); } }) .catch((error) => { console.error('Network error:', error); });
Ensure that you replace
itemIdToDelete
with the actual ID of the item you want to delete.Conclusion
Handling DELETE requests in Next.js API Routes with TypeScript is a crucial part of building full-stack web applications.
By creating dedicated API endpoints and implementing the appropriate logic, you can efficiently manage data deletions and other operations.
This approach helps you build scalable and robust web applications with Next.js and TypeScript.