0
0
NextjsHow-ToBeginner · 3 min read

How to Create a PUT API in Next.js: Simple Guide

In Next.js, create a PUT API by defining an API route file inside the pages/api folder and handling the PUT method inside the exported function. Use req.method === 'PUT' to detect the request type and respond accordingly.
📐

Syntax

To create a PUT API in Next.js, export a default function from a file in pages/api. Inside the function, check if req.method is PUT. Then, handle the request and send a response with res.status() and res.json().

  • req: The incoming request object.
  • res: The response object to send data back.
  • req.method: The HTTP method used (e.g., GET, POST, PUT).
javascript
export default function handler(req, res) {
  if (req.method === 'PUT') {
    // Handle PUT request
    res.status(200).json({ message: 'PUT request received' });
  } else {
    res.setHeader('Allow', ['PUT']);
    res.status(405).json({ error: 'Method not allowed' });
  }
}
💻

Example

This example shows a Next.js API route that updates a user's name sent in the request body using a PUT request. It responds with a success message and the updated name.

javascript
import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req, res) {
  if (req.method === 'PUT') {
    const { name } = req.body;
    if (!name) {
      return res.status(400).json({ error: 'Name is required' });
    }
    // Simulate updating user data
    res.status(200).json({ message: 'User updated', updatedName: name });
  } else {
    res.setHeader('Allow', ['PUT']);
    res.status(405).json({ error: `Method ${req.method} not allowed` });
  }
}
Output
{"message":"User updated","updatedName":"Alice"}
⚠️

Common Pitfalls

Common mistakes when creating PUT APIs in Next.js include:

  • Not checking req.method and handling other methods properly.
  • Forgetting to parse JSON body (Next.js parses JSON automatically if Content-Type is application/json).
  • Not setting allowed methods in the response header.
  • Sending responses without ending the function, causing errors.
javascript
export default function handler(req, res) {
  // Wrong: No method check
  const { name } = req.body;
  res.status(200).json({ message: 'Updated', name });
}

// Correct way:
export default function handler(req, res) {
  if (req.method === 'PUT') {
    const { name } = req.body;
    if (!name) {
      return res.status(400).json({ error: 'Name required' });
    }
    res.status(200).json({ message: 'Updated', name });
  } else {
    res.setHeader('Allow', ['PUT']);
    res.status(405).json({ error: 'Method not allowed' });
  }
}
📊

Quick Reference

Tips for creating PUT APIs in Next.js:

  • Always check req.method to handle only PUT requests.
  • Use res.status() to set HTTP status codes.
  • Send JSON responses with res.json().
  • Set Allow header for unsupported methods.
  • Next.js automatically parses JSON request bodies if Content-Type is application/json.

Key Takeaways

Create a PUT API in Next.js by checking if req.method === 'PUT' inside an API route.
Always respond with appropriate status codes and JSON messages.
Set the Allow header and handle unsupported methods with 405 status.
Next.js automatically parses JSON request bodies for you.
Avoid sending responses without ending the function to prevent errors.