question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Upload file API stopped working - middleware issue

See original GitHub issue

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #46~20.04.1-Ubuntu SMP Thu Jul 14 15:20:17 UTC 2022
Binaries:
  Node: 16.16.0
  npm: 8.1.2
  Yarn: 1.22.17
  pnpm: N/A
Relevant packages:
  next: 12.2.4
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Describe the Bug

Simply the API to upload the file stopped working. The request hangs and there is no response

image

The request does not reach the breakpoint on the API line 81 if (!request.file) {

when I remove the form-data params the API is called and of course, I get File was not provided

Expected Behavior

It should just work like before

Link to reproduction

/

To Reproduce

To reproduce here the API upload.tsx


/* eslint-disable unicorn/no-null */
import * as mime from 'mime-types'
import multer from 'multer'
import { NextApiRequest, NextApiResponse } from 'next'

export const config = {
  api: {
    bodyParser: false, // Disallow body parsing, consume as stream
  },
}

interface NextApiRequestExtended extends NextApiRequest {
  file: any
  files: any
}

const upload = multer({
  storage: multer.diskStorage({
    destination: (request, file, callback) => {
      const { isProjectPic } = request.query
      const destinationPath =
        isProjectPic === 'true'
          ? `./public/uploads/project`
          : `./public/uploads/profile`
      callback(null, destinationPath)
    },
    filename: (request, file, callback) => {
      const extension = mime.extension(file.mimetype)
      if (typeof extension === `string`) {
        const fileNames = file.originalname.split('.', 1)
        const { userId } = request.query
        if (fileNames.length > 0) {
          const fileName = fileNames[0]
            .toLowerCase()
            .replace(/\s/g, '-')
            // eslint-disable-next-line unicorn/prefer-spread
            .concat('-', userId ? (userId as string) : '', '.', extension)
          callback(null, fileName)
        }
      }
      callback(null, file.originalname)
    },
  }),
  // 1MB
  limits: { fileSize: 1 * 1024 * 1024 },
  fileFilter: (request, file, callback) => {
    if (
      file.mimetype === 'image/png' ||
      file.mimetype === 'image/jpg' ||
      file.mimetype === 'image/jpeg'
    ) {
      callback(null, true)
    } else {
      return callback(new Error('Invalid mime type'))
    }
  },
})

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(
  request: NextApiRequestExtended,
  response: NextApiResponse,
  function_: any,
) {
  return new Promise((resolve, reject) => {
    function_(request, response, (result: any) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}
const handler = async (
  request: NextApiRequestExtended,
  response: NextApiResponse,
) => {
  try {
    await runMiddleware(request, response, upload.single('image-upload'))
    if (!request.file) {
      return response.status(404).end('File was not provided')
    }
    const file = request.file
    return response.status(200).send({
      filename: file.filename,
      size: file.size,
      path: file.path,
    })
  } catch (error: any) {
    return response.status(404).end(error.message)
  }
}
export default handler

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
remorsescommented, Oct 5, 2022

I have the same problem with a POST request with a payload of 50Kb

Edit: Fixed skipping api requests in middleware, you can add the following code to middleware.js

export const config = {
    matcher: '/((?!api\/).*)',
}
1reaction
Kikobeatscommented, Oct 7, 2022
Read more comments on GitHub >

github_iconTop Results From Across the Web

Problem in Middlewares, cannot post to /api/upload
I am working on a small import system. User upload the file from frontend and Nodejs handle that file and parse data from...
Read more >
Express multer middleware
Multer is a node.js middleware for handling multipart/form-data , which is primarily used for uploading files. It is written on top of busboy...
Read more >
REST API for File Upload Services - Oracle Help Center
The Oracle Healthcare Foundation provides a set of APIs that lets you upload files securely to a particular location.
Read more >
File uploads in FeathersJS | feathers
Recently we were struggling to find a way to upload files without having to write a separate Express middleware or having to (re)write...
Read more >
Minimal APIs quick reference - Microsoft Learn
In the port setting samples that follow, running the app from ... Web root is where the static files middleware looks for static...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found