Let a browser upload to a bucket
Sign an upload link on your server so a browser sends files straight to a bucket without seeing its secret.
All pages
The browser never gets the bucket's keys. It asks your server for a link, your server signs one with the bucket's keys, and the browser sends the file to that link.
- On your server, sign a link for the file.
With a connected bucket, the service already has
S3_PUBLIC_ENDPOINT,S3_REGIONand the keys:jsimport { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; const signer = new S3Client({ region: process.env.S3_REGION, bucketEndpoint: true, requestChecksumCalculation: "WHEN_REQUIRED", credentials: { accessKeyId: process.env.S3_ACCESS_KEY_ID, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY, }, }); export async function signUpload(type) { const key = `uploads/${crypto.randomUUID()}`; const url = await getSignedUrl( signer, new PutObjectCommand({ Bucket: process.env.S3_PUBLIC_ENDPOINT, Key: key, ContentType: type, }), { expiresIn: 900 }, ); return { key, url }; }Sign it for
S3_PUBLIC_ENDPOINT: the in-project endpoint answers from inside a project's network only, so a browser can't use a link signed for it. WithbucketEndpointon,Buckettakes that endpoint instead of a bucket name.Keep
requestChecksumCalculationatWHEN_REQUIRED: the SDK's default signs a checksum into every request, and that breaks a signed upload. - In the page, get a link from your server and upload the file to it:js
const { url } = await fetch("/upload-link", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: file.type }), }).then((response) => response.json()); await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": file.type }, });/upload-linkstands for a route on your server that callssignUpload.
The secret stays on your server. The link works for the time you signed it for, here 15 minutes.
A bucket takes browser requests from any website until you list its allowed origins. An empty list means any origin: a write is gated by the signature, not by the list.
To list them, open the bucket, press ⌘K and choose Edit the allowed origins. Write one origin per line, the scheme and host only, like https://example.com. The list holds 50 origins at most. The bucket then refuses browser requests from any other origin. Ghaym never fills the list from your project's addresses: a bucket belongs to no project.