0

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.
4
  • Can you please update your question to include the tsx you're returning for that page or just the form snippet? Commented Jul 21, 2022 at 13:40
  • See this page for a full example: dev.to/smeijer/… Commented Jul 21, 2022 at 14:54
  • I just wanted to make sure that you updated your input name to match the server side props: <input name="input" defaultValue={props.input} /> Commented Jul 21, 2022 at 15:03
  • I found that it's best to use GET with forms. Post forms don't seem to be supported, and the hack I have breaks sometimes. Commented Aug 17, 2022 at 22:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Do you have an example of posting data to a new page? The original does work for me if I ignore the TS warning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.