Search code examples
javascriptreactjstypescriptnext.jshttp-proxy-middleware

Can't pass request body through next-http-proxy-middleware


I've been trying to create a frontend using nextjs for a backend I have running in Java.

I'm using the npm package next-http-proxy-middleware and it seems that either my request body is being dropped or I'm using the package incorrectly.

Here's the entirety of my ./src/api/[...all].ts file

import type { NextApiRequest, NextApiResponse } from 'next'
import httpProxyMiddleware from 'next-http-proxy-middleware'

type Data = {
  name: string
}

export const config = {
  api: {
    externalResolver: true,
  },
}

export default (req: NextApiRequest, res: NextApiResponse) => {
  httpProxyMiddleware(req, res, {
    target: `http://${process.env.REACT_APP_URL}`,
    changeOrigin: true,
  })
}

and here's the snippet of code where I attempt to login, the form that supplies this data is built using react-hook-form

const onSubmit: SubmitHandler<Inputs> = async (data: any) => {
    //console.log('username', watch('username'), 'password', watch('password'))
    const response = await axios.post(
      '/api/session',
      new URLSearchParams({
        email: data.username,
        password: data.password,
      })
    )
  }

I do see that it's connecting to my backend since I'm getting an error that's generated by my Java program and not by next.js, but it just tells me that the email is null which leads me to believe that my args are being lost in translation

"Cannot invoke \"String.trim()\" because \"email\" is null - NullPointerException (DataManager:149 < PermissionsManager:508 < SessionResource:111 < ...)"

I am able to get it working using vanilla react so I'm sure it's something I'm doing wrong in the implementation of the next-http-proxy-middleware but I've been bashing my head against the wall a little too long on this. I appreciate all the help, thanks!


Solution

  • I figured out the solution and I feel a bit silly for not realizing earlier:

    https://github.com/vercel/next.js/discussions/11036

    Nextjs comes with an automatic body parser and I had to disable it.

    export const config = {
      api: {
        externalResolver: true,
        bodyParser: false,
      },
    }