Handling ImageKit Upload Errors in Express Routes
Express route handler upload to ImageKit fail quiet or crash server. Pattern for validate, catch, clean error response. Works on any AWS host (EC2, ECS, Lambda).
Problem
Upload route call ImageKit. Network fail, bad file, wrong key → unhandled rejection. Server crash or client get hang request. Bad.
1. Validate before upload
Check file exist and type ok. Reject early. No waste ImageKit call.
javascript
1
2
3
4
5
6
7
8
9
10
11
const allowed = ['image/jpeg', 'image/png', 'image/webp'];
router.post('/upload', upload.single('image'), async (req, res, next) => {
if (!req.file) {
return res.status(400).json({ error: 'No file sent' });
}
if (!allowed.includes(req.file.mimetype)) {
return res.status(415).json({ error: 'File type not allowed' });
}
next();
});2. Wrap upload in try/catch
Async handler throw → Express 4 not catch it. Wrap, or use async wrapper.
javascript
1
2
3
4
5
6
7
8
9
10
11
12
router.post('/upload', upload.single('image'), async (req, res) => {
try {
const result = await imagekit.upload({
file: req.file.buffer,
fileName: req.file.originalname,
});
res.status(201).json({ url: result.url, fileId: result.fileId });
} catch (err) {
console.error('ImageKit upload failed:', err.message);
res.status(502).json({ error: 'Image upload failed. Try again.' });
}
});502 = upstream fail. Client know not their fault.
3. Never leak raw error
Send generic message to client. Log detail server side. Raw SDK error can show config.
4. Keys in env, not code
IMAGEKIT_PRIVATE_KEY from env. On AWS: Secrets Manager or Parameter Store. Never commit.5. Log for monitoring
Log failure with route + status. CloudWatch Logs pick up stdout. Later alarm on error count.
Takeaway
Validate early. Catch all. Generic error to client. Detail to log. Secret in AWS store.
Note: Check code against your ImageKit SDK version before publish. Method names can change. Test one bad upload, one good upload.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article