expressjs / expressjs/multer

File upload middleware does not work when I chain it with other middlewares. I get req.file = undefined

Open
#1,248 6 comments 0 reactions 0 assignees View on GitHub
question requires-triage
Dominant language
JavaScript
Stars
12.1k
Forks
1.1k
Avg merge
8d 2h
Merged PRs (30d)
21

Description

When I try to upload file **without chaining** the middlewares, the file upload **works** but when I **chain it with other middlewares** like input validation and authentication **the file does not upload** and _I get req.file/req.files object as undefined_.

Kindly help me to find what the issue is as I have been not able to find one yet.

I use postman to test the api and _have set the correct body, authorization token and form data_ but still the error persists.

Github link of the project: https://github.com/imhazard17/user_mvp

## Endpoint

```
// PUT /upl/upload
router.put('/upload', [userInputValidation, authentication, upload.single('file')], errForward(async (req, res) => {
if (!req.file) {
return res.status(404).json({ err: 'File not uploaded' })
}

return res.status(200).json({ file: req.file })
}))
```

## Authentication middleware

```
function authentication(req, res, next) {
if(!req.headers.authorization) {
return res.status(411).json({
err: 'Could not find auth token'
})
}

const authToken = req.headers.authorization.split(' ')[1]

let jwtVerifyRes

try {
jwtVerifyRes = jwt.verify(authToken, process.env.JWT_SECRET)
} catch(e) {
return res.status(403).json({
err: 'Could not authenticate user'
})
} finally {
req.locals = {}
req.locals.userId = parseInt(jwtVerifyRes)
next()
}
}
```

## Input validation middleware

```
function userInputValidation(req, res, next) {
const schema = z.object({
username: z.string().min(5).max(30)
password: z.string().min(8).max(40),
firstName: z.string().max(30).optional(),
lastName: z.string().max(30).optional(),
})

try {
schema.parse(req.body)
} catch(e) {
return res.status(411).json({
err: 'Wrong inputs recieved'
})
} finally {
next()
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.