Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params

Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method.

My setup includes prisma as my ORM and PlanetScale as my database provider.

Below is an example of the api route I have created:

import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";

type parameters = {
  req: NextRequest;
  res: NextResponse;
};

export const POST = async ({ req }: parameters) => {
  console.log(req);
  const result = await prisma.meetUp.create({
    data: {
      title: "some title here because I can't get the request body",
      description: "pls help me",
    },
  });

  return NextResponse.json(result);
};

Each req log is showing Undefined

Provided below is the front-end component utilizing this post method:

"use client";

import axios from "axios";
import { ChangeEvent, useState } from "react";

const MeetUpForm = () => {
  const [meetUp, setMeetUp] = useState({ title: "", description: "" });

  const submitData = async (e: React.SyntheticEvent) => {
    e.preventDefault();
    try {
      await axios.post("api/meet", meetUp);
    } catch (error) {
      console.error(error);
    }
  };

  const changeValue = (e: ChangeEvent<HTMLInputElement>) => {
    setMeetUp({
      ...meetUp,
      [e.target.name]: e.target.value,
    });
  };

  return (
    <form className="border-solid border-black" onSubmit={submitData}>
      <h1>Create new meet up</h1>
      <input
        type="text"
        name="title"
        placeholder="title"
        onChange={changeValue}
        value={meetUp.title}
      />
      <input
        name="description"
        type="text"
        placeholder="description"
        onChange={changeValue}
        value={meetUp.description}
      />
      <input type="submit" onChange={changeValue} value="Create" />
    </form>
  );
};

export default MeetUpForm;

I'm striving to properly fetch these params to successfully post the request body to the database.

Answer №1

Assuming you are utilizing the app router and the provided code in your response is from a route.ts file,

Make a modification to your POST handler as follows:

export const POST = async ({ req }: params) => {

revised version:

export const POST = async (req: Request) => {

Note that req is now the first argument. If you wish to access the query parameters, you can accomplish this by:

export const POST = async (req: Request) => {
  const { searchParams } = new URL(req.url)
  const id = searchParams.get('id')
}

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

A New Approach to Fetching Data in Next.js 13.2 using Sanity

Simply put, the main issue revolves around my usage of Sanity as I delve into learning it. While referencing their documentation at , they make use of getStaticProps. Unfortunately, with my utilization of Next.js 13.2 experimental app directory, this speci ...

What is the process of destructuring an array containing objects?

Examining this JSON structure: { "Person": { "UID": 78, "Name": "Brampage", "Surname": "Foo" }, "Notes": [ { "UID": 78, "DateTime": "2017-03-15T15:43:04.4072317", "Person": { ...

Is there a way to limit the keys of T to only number fields, where T[keyof T] is a number

I'm looking to restrict the field parameter within this function: function calculate<T>(source: T[], field: keyof T) { for(const item of source) { } } The goal is to ensure that item[field] will always be a number. Is there a way to ac ...

Is it acceptable to have an empty dependency array in React.useEffect?

Within my child React component, I receive an itemList prop from the parent component. This prop is an array of objects that contain data fetched from an endpoint. My goal in the child component is to enhance each object in the itemList array by adding mo ...

Updating non-data properties dynamically in a custom AG Grid cell renderer

In my grid setup, I have implemented an editor button in a column for each row and a new item creator button outside the grid. One of the requirements is that all buttons should be disabled when either the create or edit button is clicked. To achieve thi ...

Include multiple modules in next.config.js: next-images

Currently in my next.config.js file, I am exporting only one module. However, I need to export more than one module in the same file. My current file setup is as follows: const nextTranslate = require("next-translate"); module.exports = { ...nex ...

How to customize the page background color in Next JS

I am currently working on a project using Next Js and have encountered an issue. I have a global.css file set up in the project, but I need to change the background color of a specific page without affecting the rest of the project. Although I have tried u ...

Using regular expressions in TypeScript to declare modules

Is there a more efficient method to declare multiple modules in TypeScript? An example of the code I am trying to simplify is: declare module '*.png'; declare module '*.jpg'; declare module '*.gif'; declare module '*.svg ...

Using CreateMany within a Prisma Create query

Hello, I have been working on implementing a create statement that accepts an array of another model. Below are my schemas: model House { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt property_name String ...

The componentDidUpdate method ensures equality between the previous and current states

Within a dashboard, the layout data for each module (utilizing react-grid-layout) is stored separately from the module data and both are saved in a database. The Dashboard component state holds the current module data and layout data. I'm attempting t ...

What are some recommended methods for creating an under maintenance page in a ReactJS application?

I am looking to create a maintenance page for my Reactjs Application. The maintenance status information will be fetched from an API. My approach is to place the hook for calling the API in App.js like this: const getMaintenanceState = async () => { ...

Deriving a universal parameter from a function provided as an argument

My function can take in different adapters along with their optional options. // Query adapter type 1 type O1 = { opt: 1 } const adapter1 = (key: string, options?: O1) => 1 // Query adapter type 2 type O2 = { opt: 2 } const adapter2 = (key: string, opti ...

The suspense fallback fails to display when the router.refresh() function is utilized

Whenever the RefreshBtn component is clicked, all other components rerender with updated data. However, the suspense fallback does not display as intended. This is my page.jsx: const Home = () => { return( <RefreshBtn /> <Suspense f ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

Different Approaches to Authentication in Next.js

I've been working on establishing a secure authentication process for my Next.js project, but I'm feeling quite lost at the moment. Despite referencing the examples in the Next.js repository, I still have numerous queries regarding a comprehensiv ...

Customizing default attribute prop types of HTML input element in Typescript React

I am currently working on creating a customized "Input" component where I want to extend the default HTML input attributes (props). My goal is to override the default 'size' attribute by utilizing Typescript's Omit within my own interface d ...

Automatic completion of absolute paths in VS Code with the ability to click and view definitions through the configuration file js/tsconfig.json

In order to ensure that absolute paths function correctly, I have found that there are two key steps involved: the compilation process and configuring the code editor. I successfully managed the compilation aspect by utilizing babel-plugin-module-resolver ...

Limiting querySelector to a specific React component: a step-by-step guide

Is there a way to target a specific DOM element within a React component to change its color using the ComponentDidMount method? Parent component export class ListComponent extends Component<...> { render(): ReactNode { return ( ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

Custom component not rendering expected CSS style

I have successfully developed a custom web component without using any framework. I then proceeded to populate it with content from a template tag. Although I was able to manipulate the content using JavaScript, I encountered difficulties when trying to m ...