What causes parameters to be undefined when making a DELETE request in my Next.js application running on version 14.1.4?

I am encountering an issue with my DELETE mapping

export async function DELETE({params} : {params: {id: string}}) {
    try {
     const loanToDelete = await prisma.loan.findUnique({
        where: { id: parseInt(params.id) }
     })

    if (!loanToDelete) {
    return NextResponse.json({message: "Loan not found"}, {status: 404})
    }

      await prisma.loan.delete({
        where: {id: loanToDelete.id}
      })
      return NextResponse.json({message: "Loan successfully deleted"}, {status: 200})
      
    } catch (error) {
      console.error(error)
      return NextResponse.json({message: "An error occurred"}, {status: 500})
    }
  }

It appears that the params are not being read correctly in this DELETE request.

When testing this endpoint in Postman with

http://localhost:3000/api/loans/27
, I receive the following error:

TypeError: Cannot read properties of undefined (reading 'id')

This is puzzling to me as my GET mapping, which is similar except for returning an object, works fine in reading the id from params.


export async function GET(response: NextResponse, {params} : {params: {id: string}}) {
    try {
        const loan = await prisma.loan.findUnique({
            where: {id: parseInt(params.id)}
        })
        if (!loan) {
            return NextResponse.json({message: "Loan not found"}, {status: 404})
        }
        return NextResponse.json(loan, {status: 200})
    }
    catch {
        return NextResponse.json({message: "An error occurred"}, {status: 500})
    }
}

Is Next.js handling DELETE requests differently when it comes to reading params compared to GET requests?

Answer №1

When using the DELETE function, it is important to note that it accepts both Response and params arguments. It is crucial to acknowledge the necessity of accepting the params as the 2nd argument, similar to how the GET function operates:

export async function DELETE(_, {params} : {params: {id: string}}) {
     ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an interactive /robots.txt file for a Next.js application

I'm looking for a solution to dynamically respond to the /robots.txt request. To achieve this, I have chosen to utilize getServerSideProps https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering By exporting a ...

Is it necessary to add a line break after a span element generated by react, next, or bootstrap

There is a strange issue plaguing my code - I'm enclosing some text in a span tag and it's causing an unexpected line break. It's unclear whether React.js, Next.js, or Bootstrap is the culprit, but I can't seem to get rid of the pesky l ...

Utilizing Angular 2 or TypeScript to Retrieve Visitor's Location

I initially began using ServerVariables["HTTP_CF_IPCOUNTRY"] on the backend server, but it's proving to be too slow. I'm looking for an Angular or TypeScript alternative to speed things up. ...

Stopping the infinite refresh issue in your React webpack application

Every time I modify the TS file, Webpack keeps refreshing the page without stopping. The console message reads: "@ebpack 5.66.0 compiled successfully" I've searched online and experimented with various plugins, but none of them seem to solve the issu ...

Developing microfrontends using Angular involves loading and navigating a compiled package from npm

I have been struggling to find a solution to an ongoing issue and wasting time on futile attempts. Currently, I am working with Angular 15 within a microfrontend architecture. My goal is to implement a system where I can download a compiled microfrontend ...

Tips for utilizing Redux toolkit dispatch within Next.js when using SSG or SSR

I've been struggling for a while to resolve my problems with using Hook like useDispatch in either getStaticProps or getServerSideProps. I'm utilizing redux-toolkit for state management and also working with Next.js, but encountered an error when ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

"Capture the selected option from a dropdown menu and display it on the console: A step-by-step

Is there a way to store the selected value from a dropdown in a variable and then display it on the console? HTML <select class="form-control box" id="title" required> <option *ngIf="nationality_flag">{{nationality}}</option> &l ...

What are the steps for configuring Jest to make API requests?

Currently, I am in the process of testing my web page using MSW, jest, and react-testing-library. The application is developed with NextJS and JS. So far, setting up the MSW browser worker has been smooth sailing. However, when attempting to do the same f ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

The error message "SyntaxError: Cannot use import statement outside a module" popped up while working with discord.js, typescript, heroku

// Necessary imports for running the discord bot smoothly import DiscordJS, { TextChannel, Intents, Message, Channel, NewsChannel, ThreadChannel, DiscordAPIError } from 'discord.js' type guildTextBasedChannel = TextChannel | NewsChannel | ThreadC ...

The parameter type '{ src: string; thumb: string; }' cannot be assigned to the 'never' type in the argument

Sample Typescript Code: I am experiencing issues with my code and cannot comprehend this error message- Argument of type '{ src: string; thumb: string; }' is not assignable to parameter of type 'never' _albums = []; constructor( ...

When attempting to open a form in edit mode, data binding fails to work across multiple form controls

When clicking on the edit button, data is loaded into the form using [(ng-model)], however, it seems to be working correctly only for some fields and not all fields. The data is displayed in only a few fields despite receiving data for all fields. Below is ...

Can anyone suggest a simpler method for creating function signatures with multiple conditions?

In my function, the first argument now determines if the function should receive an array or not. This function is similar to Foo type stringF = (arr: false, type: 'str', value: string) => void type numberF = (arr, false, type: 'num&apo ...

Tips for dealing with strong reference cycles in TypeScript?

I have created a tree-like structure in my implementation, consisting of parent and child objects. The parents contain a list of children while the children have references to their parents, facilitating easy navigation through the tree. I am now contempla ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

Transferring information between components, specifically when one of them is a routerOutlet within an Angular application

I need to transfer data from the category component to the product component within the dashboard component. However, I am facing an issue due to the presence of a router outlet inside the product component. View Dashboard Screen dashboard.component.html ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

Leverage the new Animation support in RC 5 to animate each item in an *ngFor list sequentially in Angular 2

I have a unique component that retrieves a list of items from the server and then displays that list using *ngFor in the template. My goal is to add animation to the list display, with each item animating in one after the other. I am experimenting with t ...

Insert items into an array at a specific index in typescript

Using the map function, I am adding elements to array arr1. Is there a way to specify the starting index position in typescript? For example: If I want to add elements from the 3rd index position of the array, with the first two indices holding a value of ...