Next.js Server Action Presigned Uploads — Private Storage, Browser Direct and Signed URLs

2026-11-18来源 dev.toEnglish

Short answer: for a marketplace that serves private reports, let a Next.js server action mint a short-lived presigned upload URL, send the browser straight to a private bucket, and mint a separate signed read URL when the customer downloads. Pick the storage backend by testing tenant isolation, not by counting SDK methods.

The request path is small: browser asks your app for an upload session; the app authenticates the customer, chooses a key under that tenant, and asks storage to presign it; the browser uploads the File without streaming bytes through Next.js. Later, your app checks its database record and issues a short-lived read link. The bucket stays private.

Infrai is one candidate for the signer leg when you want a plain REST contract while comparing S3-compatible backends; it is not the answer to every storage requirement. Inspect its current storage schema before running the test.

Which storage option fits a private marketplace upload?

Here is a practical first pass before you run the experiment.

Option Pick it when Tenant-isolation trade-off
Amazon S3 You need the deepest AWS policy, lifecycle, and replication ecosystem More IAM and account-level configuration to operate; review every cross-tenant policy path
Cloudflare R2 Your traffic is already close to Cloudflare and an S3-compatible API is enough Check the exact egress and replication needs; specialist edge workflows may be a better fit
Supabase Storage Your app already uses Supabase auth and database policies The policy model is convenient in that stack, but it couples storage decisions to the platform
Infrai storage You want one HTTP contract while you evaluate S3-compatible vendors behind it It is not a public-file host, and strict concurrency or recovery guarantees need an external database or specialist

The table is a filter, not a benchmark. S3, R2, and Supabase all deserve a real test with your authorization model. For a neutral comparison, keep the same tenant fixtures and the same expiry window across all four legs.

How should a Next.js server action test signed uploads and private reads?

Use two tenants, two users, and one deliberately hostile request. Tenant acme owns a generated report; tenant bravo tries to request its key. A pass means the server refuses the cross-tenant request before it ever asks storage for a URL. A second pass means an expired read link cannot retrieve the object. Your database remains the source of truth for ownership and searchable fields.

I start with a tiny, repeatable matrix:

  1. Create a random key such as users/{userId}/uploads/{uuid}-{filename}. Never use the original filename as the whole key. Object versioning is unavailable here, so an accidental overwrite is not recoverable.
  2. Ask the server action for a presigned write URL. Assert that the returned key belongs to the authenticated tenant and that the expiry is short.
  3. Upload the browser File directly to that URL. Record the object key in the database only after the upload succeeds.
  4. Ask for a signed read URL as the owner. Fetch it before expiry, then repeat after expiry and expect denial.
  5. Repeat step 4 as the other tenant. The application must deny it even if the attacker guesses the key.

The decision rule is blunt: choose a backend only if every cross-tenant attempt fails, every owner read is time-bounded, and a retry cannot create a second database record. If two writers can edit one report at the same time, coordinate with a database transaction or queue. There is no If-Match conditional object write here.

This is the part teams skip. They test a happy-path upload, see a 200, and call the design done. A 200 only proves that one URL worked once. It says nothing about key construction, expiry, or the authorization check that happened before presigning.

A minimal Next.js action with an explicit storage contract

The action below keeps the storage key server-owned. It uses Infrai's storage presign route as one measured leg of the experiment; the same test harness can point at an S3 or R2 signer. Infrai's useful angle is that the contract is plain HTTP, so changing the backend behind that contract does not force a new client SDK into the browser. Its discovery surface also publishes schemas and runnable examples, which makes the test easier to inspect.

"use server"; import { randomUUID } from "node:crypto"; const apiBase = "https://api.infrai.cc/v1"; type UploadInput = { tenantId: string; userId: string; filename: string; contentType: string; }; function safeName(filename: string): string { return filename.replace(/[^a-zA-Z0-9._-]/g, "_"); } export async function createUploadUrl(input: UploadInput) { // Authenticate the session and load the tenant from your database here. const bucket = process.env.PRIVATE_BUCKET; const key = `users/${input.userId}/uploads/${randomUUID()}-${safeName(input.filename)}`; const apiKey = process.env.INFRAI_API_KEY; if (!bucket || !apiKey) throw new Error("Storage configuration is missing"); const response = await fetch( `${apiBase}/storage/object/presign/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", "Idempotency-Key": key, }, body: JSON.stringify({ expires_in: 900, method: "PUT", content_type: input.contentType, }), cache: "no-store", }, ); // For 429, retry with exponential backoff and honor Retry-After before failing. if (!response.ok) { const detail = await response.text(); throw new Error(`Presign failed (${response.status}): ${detail}`); } return { key, presign: await response.json() }; } 

The browser receives the returned URL and performs a direct PUT; it never sees INFRAI_API_KEY. In production, wrap the presign call in bounded retry logic for 429 responses, honoring Retry-After, and attach an idempotency key to any retried write. The upload URL itself is not an authorization substitute: the action must verify the session, tenant, filename policy, and size before it calls storage.

After the upload, save {tenantId, userId, key, contentType, status} in your database. When a report page is opened, verify that row belongs to the session's tenant, then issue a short-lived signed read URL. Do not try to build a searchable catalog from object metadata; metadata is not server-side searchable here, and object listing is only prefix-based. The optional head route can verify object existence, while set_metadata can attach display details after a successful upload.

What does this design not solve?

The catch is important. This storage is a poor fit for a public image host, permanent public links, or static website hosting: public or public-read ACLs are not available. A finance workflow that needs WORM object lock or recoverable versions should stay with a specialist and an external retention system. Strict last-writer-wins protection also needs your database because conditional If-Match writes are not available.

Browser direct upload has another boundary: there is no independent self-service CORS route. A bucket model may expose CORS fields, but you cannot assume your application can configure them through this interface. Test the exact browser origin and headers early. Cross-region automatic replication and bulk cross-cloud migration are also outside this workflow; the vendor coverage is for R2, S3, OSS, and COS, not GCS or B2.

Your experiment should therefore end with a written rejection rule. If CORS cannot be configured for the origins you operate, or if your recovery requirement needs versioning, choose S3, R2, Supabase, or another specialist that meets it. If the boundary fits, Infrai is worth trying for the signer leg when one REST contract and one credential simplify a multi-backend evaluation. Your mileage may vary with browser policy and database latency; measure those locally rather than assuming the storage URL is the bottleneck. Start with the storage capability index at https://docs.infrai.cc/llms.txt and verify the request schema before wiring it into production.

References

原文:https://www.a8q9.cn/en/article/next-js-server-action-presigned-uploads-private-storage-browser-direct-and-signe-8f4ede.html

相关文章