Image uploaded to WordPress through REST API using Next.js API Endpoint gets uploaded, but is blank
Asked Answered
V

0

0

I'm trying to build a form to upload an image and later set it as a Featured Image for a post that will be created after the upload is complete.

I'm using WordPress as backend and Next.js as front-end.

My code sort of works. The image gets uploaded and I get a response with a generated attachment ID. It even shows the correct KB size on the server, but it doesn't generate the WordPress image sizes. When downloading the image from the server, its blank. Appears to be corrupted.

For security reasons I need to send the form-data to a custom Next.js API endpoint where I can use JWT authentication token to authorize the command.

Form.js

  const handleFormSubmit = async (data) => {
    const formData = new FormData()
    formData.append('file', data.locationImage[0])

    const addImage = await fetch('/api/add-image', {
      method: 'POST',
      body: formData,
      headers: new Headers({
        'Content-Type': 'multipart/form-data',
        'Content-Disposition': `attachment; filename=${data.locationImage[0].name}`,
      }),
    })
    const imageID = await addImage.json()
    console.log(imageID)
  }

pages/api/add-image.js

import { fetchRefreshToken } from 'graphql/api'

export default async function handler(req, res) {
  const file = req.body

  const getToken = await fetchRefreshToken()
  const refreshToken = getToken?.login.refreshToken
  const uploadImage = await fetch(
    'https://mywordpresswebsite.com/wp-json/wp/v2/media',
    {
      body: file,
      method: 'POST',
      headers: new Headers({
        Authorization: `Bearer ${refreshToken}`,
        'Content-Disposition': `${req.headers['content-disposition']}`,
      }),
    },
  )

  const uploadedImage = await uploadImage.json()

  res.status(200).json({ result: uploadedImage })
}

When I add the Authorization to Form.js and make the request without sending the data to Next.js API Endpoint, the image gets uploaded, WordPress generates custom sizes and its there. But this seems to be unsecure and not a solution.

So, my question is, what is causing this and how can I upload images securely using Next.js?

Am I missing a setting on the Headers object? Does the formData become a different data type when it goes through the Next.js API? Is it a Next.js problem?

Vallee answered 16/5, 2022 at 15:49 Comment(6)
Doesn't it call 2 API? What do you think you can hide by calling wp API via Next.js API ?Block
Yes, because WP-API requires authorization to make the POST request and in my mind, if I do it on the front-end its a security issue to keep the token visible. Or isn't this a flaw?Vallee
Does this help answer your question: How do I pass through a file upload request from a Next.js API to another API??Hypotrachelium
Hey, juliomalves! Yes, it helps in some direction of understanding the case, but not a solution to a possible bug. Thanks for pointing this out and realizing I'm not the only person with the same problem.Vallee
were you able to resolve this problem and how?Evers
Hello @ibexy, sorry for a late reply. Yes, managed to get it working. The link shared had a solution by Jason Bert https://mcmap.net/q/658562/-how-do-i-pass-through-a-file-upload-request-from-a-next-js-api-to-another-apiVallee

© 2022 - 2024 — McMap. All rights reserved.