Next.js Discord

Discord Forum

Forward a post request to a custom backend

Answered
Oak shoot sawfly posted this in #help-forum
Open in Discord
Oak shoot sawflyOP
So i have this file upload page on client side which creates a FormData object that sends it to the /api/upload route. From this route i want to send the FormData further to my custom backend.

How should i forward this request? i tried something like this[1] but it works only for non binary files when i try to upload binaries it alters them for example if i upload a binary of 500kb it makes it 700kb something like that..

1. api handler:
const handler =
    async (_req: NextApiRequest, res: NextApiResponse) => {
  if (_req.method !== 'POST') return res.status(405).json({error: 'err'});
  console.log(_req)
  if (!_req.body) {
    return res.status(400).json({error: 'err'})
  }
  try {
    const formData = new FormData()

    const response = await fetch('http://localhost:8000/upload', {
      method: 'POST',
      headers: {
        'Content-Type': _req.headers['content-type'],
      },
      body: _req.body,
    })
  ...
Answered by riský
can you try using [rewrites](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites) to proxy the path?
View full answer

29 Replies

well firstly don't fetch your localips from the server: https://nextjs-faq.com/fetch-api-in-getserversideprops
ahhh the custom backend is running on the same machine (didn't realize initially)
Oak shoot sawflyOP
localhost:8000/upload is my custom backend
Yes, for testing purposes
also, you are using route handlers wrong i believe, https://nextjs.org/docs/app/building-your-application/routing/route-handlers, basicly you just return response and you don't need the second param (this is for app dir - you tagged route handlers so...)
the binary size change could be from nextjs fetch not having as good compression, but i don't see how that would affect the end result...
Oak shoot sawflyOP
Well i think it is because nextjs is parsing body and transforms it into a string format. But when i set te flag
bodyParser: flase
trying to access the body it returns "undefined"
Because when i send a file like "a.txt" it uploads correctly
can you try using [rewrites](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites) to proxy the path?
Answer
Oak shoot sawflyOP
I don't know how would it help.. so on client side i do the following post request

            var response;
            for( let i = 0; i < selectedFiles.length; i++) {
                const element = selectedFiles[i]
                body.append('file', element)
            }
            response = await fetch("api/file/uploads", {
                method: "POST",
                body,
            });

which it will be forwarded by the /api/file/uploads to my custom backend (localhost:8000). The reason why im doing this is because i want the communication with the backend to be done on server-side and not on the client-side (i'm new to NextJS hope it didn't sound dumb :D)
like how you are just getting the request and send it to your server, the rewrites can send the proxy without you much more code... but if you use response and do more with it (in that api file), then ignore my suggestion of that
Oak shoot sawflyOP
No i'm not using the response at all i just want to send the files, the only thing that i care is response code
so, then rewrites could simplify it for you...
Oak shoot sawflyOP
Yes but rewrites will guarantee that the post request will be done on server-side or on the client-side?
the post request will be done from the server
rewrites = server proxies
redirect = server redirects = client still does request
Oak shoot sawflyOP
As i understand i need to set a rewrite for /api/files/upload -> localhost:8000/upload
yeah
and your not sounding that dumb, just new to the extra features (i was once that...)
Oak shoot sawflyOP
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/file/uploads',
        destination: 'http://localhost:8000/upload'
      },
    ]
  },
}


I've tried this but nothing changed
if you remove your api route?
Oak shoot sawflyOP
I will try this also. In the meantime i discovered a workaround based on[1] in this example i get the body "unparsed":
export const config = {
  api: {
    bodyParser: false,
  }
};


async function buffer(readable: Readable) {
  const chunks = [];
  for await (const chunk of readable) {
    chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
  }
  return Buffer.concat(chunks);
}


1. https://github.com/vercel/next.js/discussions/12517
like this makes it sound easy, and has good explanations for how it proxyies: https://blog.logrocket.com/how-to-use-proxy-next-js/
Oak shoot sawflyOP
yes:)) thanks for help i will try with rewrites also it makes the code cleaner
Oak shoot sawflyOP
It works with rewrites also thanks!
Yay!, you have nice code now