Profile photos, team badges, match clips, promotional artwork and support documents all arrive through the same deceptively simple control: an upload button. But the risks are very different. A public player avatar can be resized and delivered through a CDN; a private document should never become publicly readable; a video may need a separate transcoding pipeline; and an untrusted file must not reach a production parser before it has been checked.
For sports, gaming and other high-traffic web applications, a secure file upload architecture is not just a matter of checking the file extension. It is a controlled workflow that connects identity, tenant permissions, temporary upload access, private storage, content inspection, processing and publication. This guide walks through that workflow, including a Node.js example using Amazon S3 presigned POSTs.

Why file uploads deserve their own security design
An upload endpoint accepts data that the application did not create and cannot initially trust. A malicious file may exploit an image or document parser, consume storage, overwrite another user’s object, expose private material or execute active content when served from the wrong location. Even an ordinary image can be oversized, malformed or deliberately constructed to stress a decoder.
Sports and gaming products often have several upload use cases:
- Player, team, club and user profile images.
- Competition artwork, banners and promotional assets.
- Match highlights, user-submitted clips and media attachments.
- Private support files and operational documents.
- Game assets, tournament graphics and content-management uploads.
Do not put every type into one broad upload rule. A profile image may need a small allowlist and image re-encoding. A video needs a separate size limit, asynchronous media processing and possibly multipart upload. A private document needs strict access checks and a different retention policy from public artwork.
Use a quarantine-first upload lifecycle
The most important architectural decision is to separate receiving a file from making it available. A successful transfer should mean only that bytes reached a private quarantine location—not that the file is safe or approved for use.
A practical lifecycle is:
- Request: an authenticated user asks to upload a specific type of file for a specific application resource.
- Authorize: the API checks the user’s permission and confirms that the target resource belongs to the user’s tenant or account.
- Issue upload intent: the server creates an upload record and a random object key, then returns short-lived upload credentials.
- Receive: the browser or app uploads directly to a private quarantine bucket or prefix.
- Verify: the server checks that the expected object exists and that its actual size and metadata are within policy.
- Inspect: a worker validates file signatures and content, scans where appropriate, and safely transforms supported media.
- Publish or reject: approved files are copied or promoted to a clean storage location; rejected files remain inaccessible and are deleted according to policy.
This flow makes the upload state explicit. Useful states include requested, uploaded, scanning, ready, rejected and expired. A user interface can show “processing” until the backend marks the asset as ready instead of assuming that an HTTP 200 response means the media is safe to display.
Authenticate the user and authorize the destination
Authentication answers who is making the request. Authorization answers whether that identity may upload to the selected destination. Both are necessary.
For a multi-tenant product, derive the tenant ID from the verified session or access token—not from an arbitrary tenantId supplied in the request body. Then verify that the user can modify the exact team, competition, profile or content record receiving the file. A valid account must not be able to upload into another customer’s namespace simply by changing an object path.
Keep upload permissions narrow. A user who can change a profile image should not automatically be allowed to upload executable game packages, private documents or large video files. Define separate permissions and quotas for each upload purpose. Our guide to multi-tenant SaaS architecture explains why tenant boundaries need to be enforced throughout the application rather than only in the user interface.
Validate the file using multiple signals
Never trust the browser’s filename or its Content-Type header as proof of file type. A client can rename a file or send a misleading MIME value. OWASP recommends a defence-in-depth approach: allow only required extensions, validate content type as a quick check, inspect file signatures in combination with other checks, generate server-side filenames, limit size and use malware scanning or sandboxing where available.
For a controlled image-upload feature, a policy might allow JPEG, PNG and WebP only. That policy should be enforced by the backend and repeated by the processing worker. Do not allow SVG merely because it is an image format if the application does not need it; SVG can contain active content and needs a separate sanitisation strategy.
A robust validation sequence can include:
- Decode and normalize the supplied filename before checking its extension.
- Compare the extension with an explicit allowlist for that upload purpose.
- Inspect the actual file signature or magic bytes; do not rely on the MIME header alone.
- Attempt to decode the file with a maintained library configured with resource limits.
- For images, re-encode to an approved format and remove unnecessary metadata.
- For documents, use malware scanning and consider Content Disarm and Reconstruction (CDR) where the document type and risk justify it.
- Reject archives unless the product genuinely needs them; if archives are accepted, defend against path traversal and decompression bombs.
Signature checking is useful but is not a complete security boundary. OWASP explicitly warns that file signatures should be used alongside other validation controls, not on their own. See the OWASP File Upload Cheat Sheet for the full set of controls.
Keep untrusted files away from the public web root
Do not save user uploads into a directory where the web server might execute scripts or apply application configuration. OWASP’s preferred approach is to store files on a separate host; if that is not possible, store them outside the web root and serve approved files through a controlled handler.
Object storage is a common fit because it separates application compute from file bytes and can integrate with lifecycle rules, private access policies and a content delivery network. Use a private quarantine bucket or prefix that has no public read access. Only the delivery layer should be able to read approved objects.
For private files, authorize every download or issue a short-lived signed download URL after checking the requesting user’s access. For public images, publish only the processed clean object. Avoid predictable object keys and never use a raw user filename as the storage path.
Direct-to-storage uploads with presigned URLs
Sending every file through the application server is straightforward, but it can make the API process handle large amounts of bandwidth and memory. For many applications, a browser-to-object-storage upload reduces that pressure: the backend authorizes the upload and creates a temporary capability, while the client sends the file directly to storage.
Amazon S3 presigned URLs are one example. They grant time-limited access using the permissions of the principal that generated them. They are bearer credentials: anyone who obtains the URL can use it within its validity period. S3 also documents that a presigned URL can be used more than once before expiry and that uploading to an existing key replaces that object. Therefore, use random per-upload keys, short expirations, private quarantine storage and a server-side completion workflow. Keep storage credentials separate from sports-provider credentials and apply least privilege to both; our sports API key and credential security guide explains the same server-side secret-handling principles. Do not treat a signed URL as proof that the file has been validated.
For browser-based uploads, an S3 presigned POST policy can include a content-length-range condition to constrain the accepted file size and conditions for fields such as the object key. That is useful when the application needs a storage-enforced size range rather than trusting a client-side size check. Read the official Amazon S3 POST policy documentation and S3 presigned URL guidance before implementing the exact request flow.
Node.js example: create a constrained upload intent
The following example shows the server-side start of a browser upload using AWS SDK for JavaScript v3. It uses a fixed server-generated key and a POST policy with a maximum byte range. It is a focused example, not a complete upload service: the database methods, authentication middleware, bucket policy, CORS configuration and scanning worker must be implemented for the application.
import { randomUUID } from "node:crypto";
import { S3Client } from "@aws-sdk/client-s3";
import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
const s3 = new S3Client({
region: process.env.AWS_REGION
});
const MAX_BYTES = 10 * 1024 * 1024;
export async function createUploadIntent(req, res) {
// tenantId comes from the verified session, not the request body.
const user = req.auth;
const tenantId = user.tenantId;
if (!user.permissions.includes("media:upload")) {
return res.sendStatus(403);
}
const declaredSize = Number(req.body.size);
if (!Number.isSafeInteger(declaredSize) ||
declaredSize MAX_BYTES) {
return res.status(400).json({ error: "Invalid file size" });
}
const uploadId = randomUUID();
const objectKey = `quarantine/${tenantId}/${uploadId}`;
await db.uploads.create({
id: uploadId,
tenantId,
ownerId: user.id,
objectKey,
declaredSize,
state: "requested"
});
const post = await createPresignedPost(s3, {
Bucket: process.env.UPLOAD_BUCKET,
Key: objectKey,
Expires: 60,
Conditions: [
["content-length-range", 1, MAX_BYTES]
]
});
return res.json({
uploadId,
url: post.url,
fields: post.fields
});
}
The browser submits the returned fields and file as a multipart form to the returned URL. The server should not mark the record as ready after the browser reports success. Instead, the client calls a completion endpoint, and the backend checks the stored object and moves the record to an uploaded or scanning state.
The declared size is useful for early feedback, but the signed POST policy enforces the allowed byte range at storage. The backend must still inspect the actual stored object. For a different storage provider or upload method, use that provider’s equivalent constraints; do not assume that a plain presigned PUT automatically enforces every size rule.
Make completion and scanning idempotent
Upload completion requests can be retried because a mobile connection drops or the browser does not receive the API response. A scanning worker can also restart after processing a file but before acknowledging its job. Design both operations so the same upload cannot be published twice or move backwards from ready to scanning.
Use the upload ID as a stable job identity. Make state transitions conditional in the database—for example, only transition from uploaded to scanning once. Store the scanner result, file hash, detected type, actual size and processing version. If the worker runs again, it should return the existing result or safely continue from the recorded state.
When an upload passes inspection, copy it to a clean key that the client cannot write to. This matters with reusable presigned URLs: even if an old URL is used again to replace the quarantined object before it expires, it should not be able to overwrite the approved object already published from a separate clean location.
Process large videos without exhausting application memory
Match clips, highlights and other video assets need a separate path from small images. Do not read a multi-gigabyte upload into a single Node.js buffer. Use streaming or direct object-storage uploads, enforce a file-size and duration policy, and send the object to an asynchronous media worker for inspection and transcoding.
Node.js streams provide readable, writable and transform interfaces for processing data in chunks. The pipeline() utility helps connect streams and propagate errors, which is preferable to accumulating large payloads in memory. See the Node.js stream documentation.
For very large or unreliable network transfers, multipart upload can improve resilience because individual parts can be retried. It also creates unfinished upload state that must be completed or aborted. Configure storage lifecycle cleanup for abandoned multipart uploads and keep the upload ID and part state in your own application record.
After the source file is approved, the video pipeline can create renditions, thumbnails and streaming packages. That is a different processing stage from the upload itself; see our guide to synchronizing live sports data with video streams for the separate concerns involved in live playback and event synchronization.
Separate public media from private documents
A single storage bucket can be made to work, but separate buckets or strongly separated prefixes and policies make it easier to apply different controls. Public team logos and approved profile images may be cached by a CDN. Private support documents should not be cached publicly or exposed through a guessable URL. A file’s category should determine its access policy, retention period and delivery mechanism.
For multi-tenant systems, do not assume that a prefix such as tenant-123/ provides isolation by itself. The application must verify the tenant relationship before issuing upload or download access. Storage policies should restrict the backend service role to the operations it actually needs, and the client should never receive general bucket credentials.
Operational controls: limits, scanning, logging and cleanup
Security controls need operational support. Set limits for file size, upload frequency, concurrent uploads and total storage per tenant. Apply rate limits to upload-intent and completion endpoints, and monitor repeated failures or unusual upload patterns. Keep processing queues bounded so a burst of expensive media files cannot starve the rest of the application.
Log the upload ID, authenticated user or tenant identifier, detected file type, byte size, processing state, scanner outcome and timestamps. Do not log signed URLs, access tokens, document contents or other secrets. Keep an audit trail for who uploaded, approved, rejected or deleted a file.
Run cleanup jobs for expired upload intents, rejected objects, orphaned files and incomplete multipart uploads. Set lifecycle rules for quarantine retention and define how long approved assets remain available. A failed scan should not silently become an approved asset just because a worker timed out.
Testing the upload pipeline
Test the full workflow, not just whether a valid JPEG uploads. Include files with mismatched extensions and MIME headers, malformed images, zero-byte objects, oversized payloads, duplicate completion requests, expired signed policies, cross-tenant object IDs, interrupted uploads and scanner outages.
Also test the race between upload and publication. For example, create an upload intent, upload a valid file, complete validation and then attempt to reuse the original signed capability. Confirm that the published clean object remains unchanged and that the application refuses a second completion for the consumed intent.
Our integration testing guide covers broader test planning for API-connected systems. The same discipline—repeatable fixtures, failure-path tests and observable outcomes—applies to file processing.
Implementation checklist
- Define separate policies for images, videos and private documents.
- Authenticate users and authorize the exact tenant-owned destination.
- Generate random object keys on the server; never use the supplied filename as a path.
- Keep quarantine storage private and separate from published objects.
- Allowlist only the file types the feature actually needs.
- Check extension, MIME, signature and decoded content; do not rely on one check.
- Enforce size limits at the upload mechanism and verify actual stored size.
- Use short-lived upload capabilities and protect them as bearer secrets.
- Scan and transform files asynchronously before publication.
- Make completion and worker state transitions idempotent.
- Serve private files through authorization checks or short-lived download access.
- Monitor quotas, processing queues, rejected files and cleanup jobs.
Conclusion
A secure file upload feature is a small distributed system. It has an identity boundary, a temporary write capability, an untrusted storage area, inspection workers, a publication decision and a controlled delivery path. Treating those stages separately prevents a successful transfer from being mistaken for a safe file.
For sports and gaming applications, the strongest design is one that understands the purpose of each upload, keeps tenant ownership explicit, validates the actual content, and publishes only a clean object through the correct access path. Start with a narrow allowlist and quarantine workflow, then add video processing, private-document controls and storage scaling only where the product requires them.
Frequently asked questions
Is checking the file extension enough to secure an upload?
No. Extensions and MIME headers can be manipulated. Use an allowlist together with signature checks, actual content validation, safe decoding or scanning, size limits and private storage.
Are presigned URLs secure for browser uploads?
They can be useful when tightly scoped and short-lived, but they are bearer credentials. Anyone holding one can use it within its validity period and may be able to replace the object at its key. Use unique quarantine keys and validate before publication.
Should uploaded files be stored in the application database?
Usually, store file bytes in object or file storage and keep metadata, ownership, state and checksums in the database. Database blob storage can be appropriate for specific requirements, but it introduces backup, performance and operational trade-offs.
Can users upload videos through the same endpoint as profile images?
The user experience may begin in the same interface, but videos should use a separate policy and processing pipeline with different size limits, asynchronous inspection and transcoding.