Next.js Discord

Discord Forum

How to get FormData on getServerSideProps?

Unanswered
Chelsea posted this in #help-forum
Open in Discord
Avatar
Hello.
My next.js application get 'POST' request form 3rd party application, and it send req with form data as payload.
I read the sample code written by JSP. And there are request.getParameter() methods to get form data.
Is there a method or property in getServerSideProps's parameter(context) to get form data?

17 Replies

Avatar
I assume third party application hits your Next.js api route not your page, right?
I don't think getServerSideProps is gonna be used
@Chelsea
Avatar
No. Third party application sends the form data to page.
Avatar
well, I would recommend send request (with form data) to the api route not a page
I wonder why it is - but you can still get the request body, right?
export async function getServerSideProps(context) {
    const { req } = context;

    if (req.method === 'POST') {
        const { name, email } = req.body; // Accessing the form data
        // Process the data (e.g., save to database)
    }

    return {
        props: {}, // Pass props to your page component
    };
}
like this
Avatar
I want to do like that! but there's no property error occured.
Image
Avatar
Because I can't edit the way third party sends request
Avatar
import { parseBody } from 'next/dist/next-server/server/api-utils';

export const getServerSideProps = async (context) => {
  const body = await parseBody(context.req, '1mb');

  //...
}
Avatar
Oh! Thanks
I'll try
Avatar
depending on the next.js version, import might be different
Avatar
No matter. It was very helpful.
Avatar
did it work? @Chelsea