Params in Next.js 14 API Routes and Resolving Common Errors

Params in Next.js 14 API Routes and Resolving Common Errors

Params in Next.js 14 API Routes and Resolving Common Errors

Nov 26, 2023
💡
Next.js 14 introduces enhanced support for API routes, including a simplified approach for handling dynamic URL segments. This article will guide you through the process of extracting route parameters in Next.js 14 API routes and how to resolve a common error related to parameter extraction.

Step-by-Step Guide to Accessing Route Parameters

Defining the API Route:

  • Create a file within the pages/api directory corresponding to your dynamic route. For handling a DELETE request for a role by its ID, the file path might be pages/api/roles/[id].js.

Extracting the Parameter:

Next.js 14 passes route parameters as part of the second argument to the API route function. You can access these parameters by destructuring this argument.

Here’s a full example:

import { NextResponse } from "next/server";

export async function DELETE(req, { params }) {
  // Ensure the request method is DELETE
  if (req.method !== "DELETE") {
    return new NextResponse(JSON.stringify({ success: false, error: "Method Not Allowed" }), {
      status: 405,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }

  try {
    // Extract the 'id' parameter from the route parameters
    const { id } = params;

    // Validate if the 'id' parameter is present
    if (!id) {
      // Return a 400 Bad Request response if 'id' is not provided
      return new NextResponse(JSON.stringify({ success: false, error: "Role ID not provided" }), {
        status: 400,
        headers: {
          "Content-Type": "application/json",
        },
      });
    }

    // Here, you can place your logic to handle the request
    // For example, deleting a record from a database

    // Return a 200 OK response upon successful deletion
    return new NextResponse(JSON.stringify({ success: true, message: "Role deleted successfully" }), {
      status: 200,
      headers: {
        "Content-Type": "application/json",
      },
    });
  } catch (error) {
    // Log and return an error response
    console.error(`An error occurred: ${error.message}`);
    return new NextResponse(JSON.stringify({ success: false, error: "Internal Server Error" }), {
      status: 500,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }
}

Example Output:

Resolving the "req.query is undefined" Error

A typical error encountered is TypeError: Cannot destructure property 'id' of 'req.query' as it is undefined. This error indicates an attempt to access parameters in an outdated manner.

Solution:

  • Use the Correct Parameter Access Method: Ensure that you are using the new approach provided in Next.js 14, which involves using the second argument of the API route function for parameter access.
  • Verify Route Definition: Your file and folder structure should match the dynamic route pattern correctly. For an id parameter, your file should be [id].js located in the appropriate directory.
  • Implement Proper Error Handling: Manage scenarios where the id is either not provided or invalid, by returning suitable error responses.

Anurag Deep

Logical by Mind, Creative by Heart