GuidesWeb app
Tutorial: uploading files to S3 with a signed URL
1. Sign (server)
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { randomUUID } from 'node:crypto';
const s3 = new S3Client({ region: process.env.S3_REGION, endpoint: process.env.S3_ENDPOINT });
export async function sign(type: string, size: number) {
if (!['image/jpeg', 'image/png', 'application/pdf'].includes(type)) throw new Error('type refused');
if (size > 10 * 1024 * 1024) throw new Error('too large');
const key = `uploads/${randomUUID()}`;
const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: process.env.S3_BUCKET, Key: key, ContentType: type }), { expiresIn: 300 });
return { url, key };
}
2. Upload (browser)
const { url, key } = await (await fetch('/api/sign', { method: 'POST', body: JSON.stringify({ type: f.type, size: f.size }) })).json();
await fetch(url, { method: 'PUT', body: f, headers: { 'Content-Type': f.type } });
await fetch('/api/files', { method: 'POST', body: JSON.stringify({ key }) }); // record it
3. The settings that matter
- Bucket CORSAllow PUT from your domain only.
- Private bucketReads go through signed URLs too.
- Key chosen by the serverNever the user's file name.
- Short expiryA few minutes are enough.
The big picture: building a web app.
Frequently asked questions
- Why not send the file to my server?
- A heavy file ties up the server, its memory and its bandwidth. With a signed URL, the storage receives the file directly.
- Can the user upload anything?
- The server decides the allowed name, type and size before signing. After the upload, check the actual file before using it.
- Does it work outside Amazon?
- Yes, with any S3-compatible storage: just change the endpoint address in the client.