Jason
Jason

Reputation: 551

How to get post data in NextJS with Typescript?

I wrote a function to get posted form data in a NextJs page. While this works, the req and res parameters aren't typed:

const getBody = promisify(bodyParser.urlencoded());

export async function getServerSideProps({ req, res }) {

  if (req.method === "POST") {
    await getBody(req, res);
  }

  return {
    props: {
      input: req.body?.input
    }
  }
}

I've tried using req: NextApiRequest, res: NextApiResponse with an interface but the function body won't work:

interface ExtendedNextApiRequest extends NextApiRequest {
  body: {
    input: string;
  };
}

export async function getServerSideProps(req: ExtendedNextApiRequest, res: NextApiResponse) {

  if (req.method === "POST") {
    await getBody(req, res);
  }

  return {
    props: {
      input: req.body?.input
    }
  }
}

However I get a serialization error:

Error: Error serializing `.input` returned from `getServerSideProps` in "/my-page".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

Upvotes: 0

Views: 1503

Answers (1)

rgodha24
rgodha24

Reputation: 61

Your problem is that you are using getServerSideProps as an API endpoint. getServerSideProps is meant to be be used to fetch data from an API endpoint or backend logic and pass it to the function component, so it can not handle post methods. If you want to make an API endpoint, you can make a function in the /pages/api directory. You can strong type that like this:

import type { NextApiHandler } from "next";

let handler: NextApiHandler<any> = async (req, res) => {
    // your code goes here
};

export default handler;

where the any can be replaced by the type of the api response.

Upvotes: 1

Related Questions