Building a feature-rich web application often requires simple yet effective solutions. One such example is managing uploaded images in memory, specifically camera screenshots. Here, I’ll walk you through how to create an Express.js endpoint that stores and retrieves screenshots from memory. This setup is ideal when you want lightweight, temporary storage for uploaded files without persisting them on disk.
Thank me by sharing on Twitter 🙏
Setting Up the Endpoint for Uploads
To handle file uploads in Express, I rely on the multer
library. Multer makes it incredibly easy to manage file uploads in a structured way. For our use case, I’ll configure it to store files directly in memory. This keeps things fast and simple.
Here’s how the endpoint looks in TypeScript:
import express from 'express';
import multer from 'multer';
const app = express();
const port = 3000;
// Configure Multer to use memory storage
const storage = multer.memoryStorage();
const upload = multer({ storage });
// In-memory storage for screenshots
let screenshotBuffer: Buffer | null = null;
// POST endpoint to upload a screenshot
app.post('/upload', upload.single('screenshot'), (req, res) => {
if (!req.file) {
res.status(400).send('No file uploaded.');
return;
}
// Store the screenshot in memory
screenshotBuffer = req.file.buffer;
res.send('Screenshot uploaded successfully.');
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Breaking Down the Code
- Memory Storage with Multer:
Usingmulter.memoryStorage()
ensures that files are stored temporarily in memory as buffers. This is perfect for cases where you don’t need permanent storage. - Single File Upload:
Theupload.single('screenshot')
middleware processes one file at a time. It expects the form field carrying the file to be namedscreenshot
. - Handling Errors:
If no file is uploaded, I return a400 Bad Request
response. This ensures the client knows something went wrong.
Retrieving the Uploaded Screenshot
Once an image is uploaded, I want a way to retrieve it. This is where the GET endpoint comes into play. It serves the screenshot stored in memory if one exists.
Here’s the code for the retrieval endpoint:
uni SD Card Reader, High-Speed USB C to Micro SD Card Adapter USB 3.0 Dual Slots, Memory Card Reader for SD/Micro SD/SDHC/SDXC/MMC, Compatible with MacBook Pro/Air, Chromebook, Android Galaxy
$7.99 (as of February 25, 2025 13:13 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)iPhone Charger 3 Pack 10 ft Apple MFi Certified Lightning Nylon Braided Cable Fast Charging Cord Compatible with iPhone 13 12 11 Pro Max XR XS X 8 7 6 Plus SE iPad and More
$9.99 (as of February 25, 2025 13:13 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)[Apple MFi Certified] 6Pack 3/3/6/6/6/10 FT iPhone Charger Nylon Braided Fast Charging Lightning Cable Compatible iPhone 14 Pro/13 mini/13/12/11 Pro MAX/XR/XS/8/7/Plus/6S/SE/iPad
$8.99 (as of February 25, 2025 13:13 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)// GET endpoint to retrieve the stored screenshot
app.get('/screenshot', (req, res) => {
if (!screenshotBuffer) {
res.status(404).send('No screenshot available.');
return;
}
// Respond with the screenshot buffer
res.set('Content-Type', 'image/png');
res.send(screenshotBuffer);
});
How It Works
- Buffer Validation:
Before sending the file, I check whether a screenshot exists in memory. If the buffer is empty, a404 Not Found
response is returned. - Serving the File:
TheContent-Type
header ensures that the response is treated as a PNG image. This can be modified to other formats if needed.
Testing the Endpoints
With the server running, I typically use tools like Postman to test both endpoints. Here’s how I do it:
- Uploading a Screenshot:
Send aPOST
request to/upload
with a file in thescreenshot
form field. The response confirms whether the upload was successful. - Retrieving the Screenshot:
Send aGET
request to/screenshot
. If an image has been uploaded, the server responds with the image data. Otherwise, you get a404
.
Key Features of This Approach
One thing I appreciate about this setup is its simplicity. Since the screenshot is stored in memory, there’s no need to manage file paths or clean up unused files. It’s a lightweight solution that works well for prototypes or temporary file handling.
That said, storing files in memory has its limitations. Memory usage increases with larger files, and the data is lost when the server restarts. If you need persistent storage or plan to handle large files, consider integrating a more robust solution like a cloud storage service.
Conclusion
Creating an Express.js endpoint for handling screenshots is a straightforward yet powerful feature to include in your application. By using multer
and memory storage, you can quickly set up a temporary and efficient file handling system. Whether you’re working on a quick prototype or a project where simplicity is key, this approach gets the job done with minimal effort and maximum clarity.