Secure File Upload Method with Fastify.js
Secure File Upload Method with Fastify.js
Introduction to File Upload with Fastify.js
Fastify.js, which is rapidly increasing in popularity in the Node.js world for its performance and security, stands out with its low resource consumption and plugin support. To allow users to upload files (file upload) in your API or web applications, you can easily set up a secure file upload system using Fastify.js. In this article, we will examine step by step how to perform a file upload operation with Fastify.js.
How to Perform File Upload with Fastify.js?
To integrate the file upload feature into your Fastify.js project, you should first install the @fastify/multipart plugin. This plugin allows you to manage incoming multipart/form-data requests. Here is a sample setup and code example for those who want to start from scratch:
// fastify-file-upload.js
const fastify = require('fastify')();
const path = require('path');
const fs = require('fs');
// Multipart plugin installation
fastify.register(require('@fastify/multipart'));
fastify.post('/upload', async function (req, reply) {
const data = await req.file();
const filePath = path.join(__dirname, 'uploads', data.filename);
await pumpStream(data.file, fs.createWriteStream(filePath));
reply.send({ success: true, filename: data.filename });
});
async function pumpStream(source, dest) {
return new Promise((resolve, reject) => {
source.pipe(dest);
dest.on('finish', resolve);
dest.on('error', reject);
});
}
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err;
console.log(`Server is running: ${address}`);
});
In this example, the incoming file is securely saved to the server's uploads directory with Fastify.js. Thanks to @fastify/multipart, the file stream is easily managed. Also, make sure that the uploads folder exists in your project root directory.
A Simple HTML Form for the Frontend
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
By connecting this HTML form to the backend server you set up with Fastify.js, you can test file uploading.
Security in File Upload Operations
When performing file uploads with Fastify.js, make sure to accept only trusted file types. You can check the type of file received from the user with data.mimetype, and prevent excessive file uploads by using the limits setting. You can also rename the file to be uploaded on the server to prevent potential security vulnerabilities.
// Only accept image files
if (!['image/png', 'image/jpeg'].includes(data.mimetype)) {
return reply.status(400).send({ error: 'Invalid file type.' });
}
Conclusion: Practical File Upload with Fastify.js
With Fastify.js, file upload operations can be performed both efficiently and securely. Thanks to plugin support, you can easily set up single or multiple file uploads. With correct security measures, Fastify.js offers ideal solutions for your file upload needs in modern Node.js projects.

Yorum Gönder