Next.js Discord

Discord Forum

No response is returned from route handler Next.js 14.2.3

Answered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
In the newer Next.js 14.2.3, I am trying to return a base 64 response via route.js. From the backend, I get a buffer response through pdf.pipe and pdf.end() functions of pdfmake. I also receive the buffer in the front end on using arrayBuffer(). But when converted and passed as base64 in the response, I get No response is returned from route handler. I need to know is this the way to handle base64 files or is there another way.

The below is the code I am using in route.js

await fetch(demo/generate/pdf, {
method: "POST",
body: JSON.stringify(body),
headers: {
...req?.headers,
"Content-Type": "application/json",
},
}) // returns buffer from pdf.end() function in pdfmake
.then((response) => {
return response.arrayBuffer()
})
.then((buffer) => {

const b64 = Buffer.from(buffer).toString("base64");
return Response(b64)
})
.catch((err) => console.error(err));
Answered by joulev
const res = await fetch(`demo/generate/pdf`, {
    method: "POST",
    body: JSON.stringify(body),
    headers: {
        ...req?.headers,
        "Content-Type": "application/json",
    },
});
const buffer = await res.arrayBuffer();
const b64 = Buffer.from(buffer).toString("base64");
return new Response(b64);
View full answer

5 Replies

Sun bear
I am not sure if I understood the problem correct but I think you can try:

const image = await fetch(...)

return Response.json({ image })
@Sun bear I am not sure if I understood the problem correct but I think you can try: js const image = await fetch(...) return Response.json({ image })
American black bearOP
This doesn't work for base64 since we are trying to return the response as json.
Answer
@American black bear That worked! Can you explain what is the difference between your's and mine?
async function foo() {
  return "foo";
}

async function working() {
  const result = await foo();
  return result;
}

async function notWorking() {
  await foo().then(result => {
    return result;
  });
}

async function workingButWorse() {
  return await foo().then(result => {
    return result;
  });
}

console.log(await working()); // "foo"
console.log(await notWorking()); // undefined
console.log(await workingButWorse()); // "foo"