DEV Community

RadcliffBarrett4718
RadcliffBarrett4718

Posted on

Vue Frontend Direct File Upload with Presigned URLs for Private Storage and Axios

Short answer: let the browser send bytes to a private object store with a short-lived presigned URL, while Node owns tenant-scoped keys and Vue reports transport progress. Treat the progress bar as a hint, then use storage events and checksums to decide whether the upload is actually usable.

Option Pick it when Main risk to test
App-proxy upload Files are small, or the app must transform every byte Web servers become a bandwidth and timeout bottleneck
Browser direct upload Large media should bypass the Node process A leaked or overly broad grant can cross tenant boundaries
Resumable session Mobile clients and multi-gigabyte media are normal Session state, expiry, and retry cleanup get complicated

The table is a decision aid, not a vendor scorecard. For a B2B SaaS product with customer video, direct upload is usually the least complex path once the authorization boundary is explicit.

What should a Vue frontend upload flow prove before showing success?

A useful mental diagram is: Vue asks Node for a grant; Node authenticates the user and derives a key from the tenant; the browser uploads to private storage; Node (or a storage event consumer) verifies the resulting object. The arrow carrying bytes never passes through the application server.

The grant should name one object, one method, and a short expiry. Never accept a client-supplied bucket path as an authorization decision. Build the key from server-side identity, for example tenants/${tenantId}/media/${uploadId}. Keep the opaque uploadId in your database with the expected size, MIME family, and owner before issuing the URL. That record is useful during support calls: an operator can trace a missing thumbnail from the browser correlation ID to the grant, then to the storage event, without opening a customer's private object. It also gives the cleanup job a precise boundary, because an abandoned upload is a database state with an owner and timestamp, not an unsearchable blob in a shared bucket.

Keep it boring.

Here is the shape of a Node endpoint. It intentionally returns a capability, not storage credentials.

import crypto from "node:crypto";
import type { Request, Response } from "express";

export async function createUploadGrant(req: Request, res: Response) {
  const tenantId = req.user.tenantId;
  const uploadId = crypto.randomUUID();
  const key = `tenants/${tenantId}/media/${uploadId}`;
  const expectedBytes = Number(req.body.size);

  if (!Number.isSafeInteger(expectedBytes) || expectedBytes <= 0) {
    return res.status(400).json({ error: "invalid size" });
  }

  await db.uploads.insert({ uploadId, tenantId, key, expectedBytes, state: "pending" });
  const url = await objectStore.createPresignedPut({
    key,
    contentType: req.body.contentType,
    expiresInSeconds: 300,
  });

  return res.json({ uploadId, url, key });
}
Enter fullscreen mode Exit fullscreen mode

The storage policy must prevent a principal used by one tenant from reading another tenant's prefix. A database lookup on every download is still valuable: storage isolation protects bytes, while the database protects product-level ownership and deletion rules.

How do Vue, Axios, presigned URLs, and private object storage fit together?

The browser first calls the application endpoint, then sends the file directly to the returned URL. Axios exposes onUploadProgress; it measures bytes accepted by the browser's HTTP stack, so it can reach 100% before the storage service has completed its final write. That is normal. Display “uploading” until your confirmation step finishes.

import axios from "axios";

export async function uploadMedia(file: File, onPercent: (value: number) => void) {
  const { data } = await axios.post("/api/media/grant", {
    size: file.size,
    contentType: file.type || "application/octet-stream",
  });

  await axios.put(data.url, file, {
    headers: { "Content-Type": file.type || "application/octet-stream" },
    onUploadProgress: (event) => {
      if (event.total) onPercent(Math.round((event.loaded / event.total) * 100));
    },
  });

  const { data: confirmed } = await axios.post("/api/media/confirm", {
    uploadId: data.uploadId,
  });
  return confirmed;
}
Enter fullscreen mode Exit fullscreen mode

Keep the URL out of application logs and analytics. Redact query strings in error reporting. A URL that expires in five minutes is still a bearer capability during those five minutes, so cancellation and replacement need explicit state transitions: pending, uploaded, confirmed, rejected, or expired.

For private delivery, return a separate short-lived read URL after checking the viewer's tenant. Do not make the uploaded object public just to simplify a preview. Cache-Control belongs on the response policy you choose for those reads; MDN documents how directives affect shared and private caches, and media with tenant-sensitive data should be tested with an actual CDN configuration.

Which signals catch tenant-isolation failures early?

Logs should carry tenantId, uploadId, operation, byte count, and a correlation ID, but never the presigned query string. Metrics worth keeping are grant latency, PUT duration, confirmation latency, bytes uploaded, and the ratio of uploaded to confirmed. Alert on a rising confirmation gap, not only on HTTP failures.

I once treated a browser progress event as the source of truth and investigated a “stuck” upload that was already stored. The missing signal was confirmation. A three-word state label fixed the confusion: “Finalizing in storage.”

Use a test matrix that deliberately swaps identities: issue a grant as tenant A, attempt a read as tenant B, replay an expired URL, change the content type, and confirm an unknown uploadId. Each case should produce an auditable denial without revealing whether another tenant's key exists. Property-based tests can generate random tenant and object IDs so a path-join bug does not hide behind one fixture.

For large media, add resumable behavior only after measuring failures on real networks. A retry must reuse the same uploadId and key, not request a fresh random object for every attempt. Garbage collection can remove pending objects after a retention window; it should not delete a confirmed object merely because a client tab closed.

Where does this direct-upload design stop being a good fit?

The catch is operational ownership. Your team now owns grant policy, CORS, lifecycle cleanup, event delivery, and a confirmation worker. Direct upload is not suitable when every byte must be synchronously inspected by application code, or when your storage provider cannot enforce the required private-prefix policy. Stick with an app proxy for small, mandatory transformations; choose a resumable protocol when interrupted transfers are the dominant failure mode.

Your mileage may vary on progress accuracy across browsers and network paths. Measure it. The durable contract is the confirmed object plus its tenant record, not the number painted in a progress bar.

References

Top comments (0)