I'm trying to crop an image in a Next.js app, send it to an API route in the app and finally onto an API endpoint outside of the app. If I bypass the API route, it works OK, but not when going via it. The image data is no longer correct and can't be processed.
Client (Next.js) --> API route (Next.js) --> API Endpoint (External)
Client (Next.js) - fetch using FormData via POST
async function handleSave(image: Blob) {
const file = new File([image], 'avatar.png', { type: 'image/png' })
const data = new FormData()
data.append('imageFile', file)
const response = await fetch(`/api/users/${userId}/media/avatar`,
{
body: data,
method: 'POST',
}
)
// const response = await fetch (`https://localhost:1337/user/${userId}/media/avatar`, {
// method: 'POST',
// headers: {
// "Authorization": `Bearer <JWT token>`,
// },
// body: data
// })
if (response.ok) {
// handle
}
}
The commented out fetch is where I tested directly calling the external API Endpoint, this works OK.
API Route (Next.js) - take the request from the client side and forward it onto the external API endpoint.
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
await cors(req, res)
const { userId } = req.query;
const { accessToken } = await getToken({ req, secret });
const response = await fetch(`${process.env.API_HOST}/user/${userId}/media/avatar`, {
method: 'POST',
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": req.headers["content-type"]
},
body: req.body
})
try {
const json = await response.json();
console.log(json)
}
finally { }
res.end()
}
API Endpoint (External)
- ASP.Net Core Web API
- Request should be
multipart/form-data - Request should contain image in the
imageFileand is mapped toIFormFile
Once the request is passed through the API route and sent on to the external API, the image stream is no longer valid. I can see the IFormFile object has picked up the imageFile OK and got the relevant data.
When I bypass the Next.js API route, the upload works fine and I have noted that the IFormFile object length is much smaller.
Going via the Next.js API route is important because it handles passing the access token to the external API and it's not intended to expose that API.
I've taken a look at Create upload files api in next.js, but I'm not sure how/if formidable fits for this scenario?

