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

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

Utilizing Typescript with tfjs-node to effectively integrate the node-gpu version with regular node functionalities

I am facing challenges while running my Tensorflow.js node application with and without the GPU library. In vanilla JavaScript, examples show using require() for either @tensorflow/tfjs-node or @tensorflow/tfjs-node-gpu. However, in my TypeScript setup, I ...

The error message "TypeError: Unable to access the 'getFullWidth' property of an undefined value when using TSLint and TypeScript" was

I have been using Dan Wahlin's tutorials and online examples to set up Gulp and Typescript, but I am facing an issue with the tslint() function. The problem occurs in my code as follows: node_modules\tslint\lib\language\walker&bso ...

How can we dynamically update property values in a ngFor loop by utilizing the click method?

Here is a TypeScript file I am working with: <md-card style="display: inline-block;" *ngFor="let people of peoples"> <p> {{people.name}} </p> <p *ngIf="people.showAge"> {{people.age}} </p> < ...

Guidelines for creating a dynamic filter in Prisma js

I am looking to create a dynamic filter based on user input from the frontend. On mapping the data, I found that the object results appear like this: { id: '2', name: 'yuhu' } The keys 'id' and 'name' need to be dyn ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

The attempt to convert the value "[]" to an Array at the specified path "pathname" failed due to a "TypeError" issue

I'm currently building a social media project using next.js and I'm looking to add an unfollow feature to my application. Encountering the following error message --> CastError: Cast to Array failed for value "[]" (type Array) at p ...

Pre-fetch page data in Next.js before rendering it

I need help optimizing my heavy web page with numerous images. How can I implement a loader to preload the page data before displaying it? Currently, I am working with Next.js. One possible solution I came up with is: const AboutPage = () => { const ...

React canvas losing its WebGL context

What is the best practice for implementing a webglcontextlost event handler for React canvas components? class CanvasComponent extends React.Component { componentDidMount() { const canvasDOMNode = this.refs.canvas.getDOMNode(); DrawMod ...

Having trouble customizing the redirect URL for the Google Auth provider popup in Vercel Deployment and Firebase Authentication

I have a question regarding my NextJS app, which utilizes cloud Firestore and Firebase authentication. The app is deployed using Vercel, with the domain also registered through Vercel. Deployment : Vercel Domain : Vercel Authentication : Firebase Authenti ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

Trouble accessing session cookie during server-side request with getServerSideProps in Next.js

I'm currently facing an issue where I am trying to make a request to a backend service using Axios in getServerSideProps, but it is unsuccessful because the necessary session cookie for authentication is not included in the context.req headers. In th ...

The lazy loading feature in Angular 12 is not functioning correctly for path modules

My application has a jobs module with various components, and I'm trying to lazy load it. However, I've encountered an issue where accessing the module through the full path http://localhost:4200/job/artist doesn't work, but accessing it thr ...

I am looking to dynamically load a script only after retrieving specific data from a JSON file in Next.js

I am trying to ensure that the Script tag loads after the data.post.content is loaded within the HTML. Specifically, my goal is to execute the MathJax.js script inside the HTML. This is the code I have: return ( <div> <h1>{data.post ...

Check for user authentication in Next.js when integrating with Express backend

Within a different project, I've set up the following endpoint using expressjs as my backend: http://localhost:3001/auth/login # to login { username: string, password: string } http://localhost:3001/auth/whoami # to check if you're logged in or n ...

In what way can data be retrieved from within a useEffect block externally?

Essentially, I'm facing an issue with retrieving data from the DateView component in my ChooseCalendar component. The code that retrieves this data is located within a useEffect block due to passing a dateType variable as part of a useState to the com ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

Struggle with implementing enums correctly in ngSwitch

Within my application, I have implemented three buttons that each display a different list. To control which list is presented using Angular's ngSwitch, I decided to incorporate enums. However, I encountered an error in the process. The TypeScript co ...

Avoiding caching of GET requests in Angular 2 for Internet Explorer 11

My rest endpoint successfully returns a list when calling GET, and I can also use POST to add new items or DELETE to remove them. This functionality is working perfectly in Firefox and Chrome, with the additional note that POST and DELETE also work in IE ...