사전 서명 URL을 사용한 S3 직접 업로드
API에서 수명이 짧은 사전 서명 URL을 발급해 대용량 업로드를 객체 저장소로 오프로드합니다
사전 서명 URL을 사용한 S3 직접 업로드은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Not Proxy Uploads Through the API?
When a client uploads a large file, the naive design sends the bytes to your NestJS API, which then forwards them to object storage. This makes your server a bottleneck.
- Memory & CPU pressure — every upload occupies a request thread and buffers/streams through your process.
- Doubled bandwidth — bytes travel client → API → S3, so you pay for the same data twice.
- Request timeouts — load balancers (e.g. ALB, Nginx) cap request duration; multi-GB uploads stall.
The fix: let the browser upload directly to S3. Your API only issues a short-lived, signed URL that grants permission for one specific operation.
What Is a Presigned URL?
A presigned URL is a normal S3 object URL with extra query parameters that encode a temporary, cryptographically-signed grant. Anyone holding the URL can perform exactly one operation (e.g. PutObject) on exactly one key, until it expires.
- Signed with your AWS credentials, but the credentials are never exposed — only the signature is.
- Scoped to a single HTTP method, bucket, and object key.
- Has a hard expiry (seconds), after which S3 rejects it with
403.
Because S3 validates the signature itself, your API does not touch the file bytes at all.
The Upload Flow
The end-to-end flow has three actors: the browser, your NestJS API, and S3.
- 1. Request: Browser asks the API, "I want to upload
avatar.png, 240 KB, image/png." - 2. Sign: API validates the request, generates a unique key, and returns a presigned
PUTURL. - 3. Upload: Browser
PUTs the raw bytes straight to that URL on S3. - 4. Confirm: Browser tells the API the upload succeeded; API persists the key in the database.
Your API stays fast and stateless — it never proxies the payload.
Configuring the S3 Client
Use the AWS SDK v3 modular packages. Create a single S3Client instance and share it via a NestJS provider so credentials and region are configured in one place.
Credentials come from environment variables (or, in production, an IAM role). Never hardcode them.
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { S3Client } from '@aws-sdk/client-s3';
@Injectable()
export class S3Provider {
readonly client: S3Client;
readonly bucket: string;
constructor(private readonly config: ConfigService) {
this.bucket = config.getOrThrow<string>('S3_BUCKET');
this.client = new S3Client({
region: config.getOrThrow<string>('AWS_REGION'),
credentials: {
accessKeyId: config.getOrThrow<string>('AWS_ACCESS_KEY_ID'),
secretAccessKey: config.getOrThrow<string>('AWS_SECRET_ACCESS_KEY'),
},
});
}
}Generating a Presigned PUT URL
The @aws-sdk/s3-request-presigner package signs a command without executing it. You build a PutObjectCommand describing the target key and content type, then call getSignedUrl with an expiresIn.
- ContentType in the command is enforced: the browser must send a matching
Content-Typeheader. - expiresIn is in seconds — keep it short (60–300s) so leaked URLs die quickly.
import { Injectable } from '@nestjs/common';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { S3Provider } from './s3.provider';
@Injectable()
export class UploadsService {
constructor(private readonly s3: S3Provider) {}
async createUploadUrl(key: string, contentType: string): Promise<string> {
const command = new PutObjectCommand({
Bucket: this.s3.bucket,
Key: key,
ContentType: contentType,
});
return getSignedUrl(this.s3.client, command, { expiresIn: 120 });
}
}Generating Safe, Unique Object Keys
Never trust the client's filename as the S3 key. A user could send ../../etc/passwd or collide with another user's file. Generate the key server-side.
- Namespace by owner:
uploads/{userId}/...so authorization is easy to reason about. - Use a random UUID to guarantee uniqueness.
- Preserve only a sanitized extension for content-type hints and tooling.
import { randomUUID } from 'node:crypto';
import { extname } from 'node:path';
function buildObjectKey(userId: string, originalName: string): string {
const ext = extname(originalName).toLowerCase().replace(/[^.a-z0-9]/g, '');
const safeExt = /^\.[a-z0-9]{1,8}$/.test(ext) ? ext : '';
return `uploads/${userId}/${randomUUID()}${safeExt}`;
}
console.log(buildObjectKey('user-42', 'My Vacation Photo.PNG'));
console.log(buildObjectKey('user-42', 'sneaky/../../etc/passwd'));The Controller Endpoint
Expose a guarded endpoint that takes the file metadata, validates it with a DTO, and returns the presigned URL plus the final key. The client needs the key later to confirm or to build the public/read URL.
Authentication matters here: the signing endpoint is your access-control gate. S3 itself trusts any valid signature, so all checks (who, what size, what type) must happen before you sign.
import { Body, Controller, Post, UseGuards, Req } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { UploadsService } from './uploads.service';
import { CreateUploadDto } from './dto/create-upload.dto';
@UseGuards(JwtAuthGuard)
@Controller('uploads')
export class UploadsController {
constructor(private readonly uploads: UploadsService) {}
@Post('presign')
async presign(@Req() req, @Body() dto: CreateUploadDto) {
return this.uploads.presignForUser(req.user.id, dto);
}
}Validating the Upload Request DTO
Validate metadata before signing. Reject disallowed MIME types and oversized files at the API layer — but remember the client could lie, so this is a first line of defense, not the last.
- Whitelist
contentTypeagainst an allow-list. - Cap the declared
sizeto fail fast on obviously huge uploads.
import { IsIn, IsInt, IsString, Max, Min } from 'class-validator';
const ALLOWED = ['image/png', 'image/jpeg', 'image/webp', 'application/pdf'] as const;
export class CreateUploadDto {
@IsString()
filename: string;
@IsIn(ALLOWED)
contentType: (typeof ALLOWED)[number];
@IsInt()
@Min(1)
@Max(10 * 1024 * 1024) // 10 MB
size: number;
}Enforcing Size with a Signed Content-Length
The DTO size check is advisory — the browser still controls how many bytes it actually PUTs. To make S3 itself reject oversized uploads, bind a content-length range into the signature.
For a single PUT, sign ContentLength so S3 enforces an exact byte count. For more flexible limits (a min/max range), use a presigned POST policy instead, which supports content-length-range conditions.
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
async function presignPost(client, bucket: string, key: string) {
return createPresignedPost(client, {
Bucket: bucket,
Key: key,
Conditions: [
['content-length-range', 1, 10 * 1024 * 1024], // 1 byte – 10 MB
['starts-with', '$Content-Type', 'image/'],
],
Fields: { 'Content-Type': 'image/png' },
Expires: 120,
});
}The Browser-Side Upload
With the presigned PUT URL in hand, the browser uploads with a plain fetch. There is no SDK and no AWS credentials on the client — just the bytes and a matching Content-Type.
- The header must equal the
ContentTypeyou signed, or S3 returns403 SignatureDoesNotMatch. - Do not send
Authorization— the signature lives in the query string.
async function uploadFile(presignedUrl: string, file: File): Promise<void> {
const res = await fetch(presignedUrl, {
method: 'PUT',
headers: { 'Content-Type': file.type },
body: file,
});
if (!res.ok) {
throw new Error(`Upload failed: ${res.status} ${res.statusText}`);
}
}Confirming the Upload & Reading Back
Because S3 doesn't notify your API, the client calls back after a successful PUT so you can persist the key. For extra safety, the API can HeadObject to verify the object truly exists and check its real size/type before trusting it.
To serve the file later, either keep the bucket private and issue a presigned GET URL on demand, or (for public assets) store and return the public URL.
import { GetObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
async confirm(userId: string, key: string) {
const head = await this.s3.client.send(
new HeadObjectCommand({ Bucket: this.s3.bucket, Key: key }),
);
if ((head.ContentLength ?? 0) > 10 * 1024 * 1024) {
throw new BadRequestException('Object exceeds size limit');
}
await this.files.save({ userId, key, size: head.ContentLength });
}
async downloadUrl(key: string) {
return getSignedUrl(
this.s3.client,
new GetObjectCommand({ Bucket: this.s3.bucket, Key: key }),
{ expiresIn: 300 },
);
}Quick Check
Test your understanding of where access control lives in this pattern.
Recap
You learned how to offload heavy uploads to S3 using presigned URLs:
- Why: proxying bytes through the API wastes bandwidth, memory, and hits request timeouts.
- How: the API signs a short-lived
PutObjectCommandwithgetSignedUrl; the browserPUTs straight to S3. - Keys: always generate them server-side (UUID + namespaced by user); never trust client filenames.
- Security: the presign endpoint is the access-control gate — authenticate, whitelist MIME types, and cap size there. Use presigned POST
content-length-rangeto let S3 enforce size. - After upload: confirm with
HeadObject, persist the key, and serve later via presignedGetObjectCommandURLs.
자주 묻는 질문
“사전 서명 URL을 사용한 S3 직접 업로드” 강의는 무료인가요?
네 — “사전 서명 URL을 사용한 S3 직접 업로드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“사전 서명 URL을 사용한 S3 직접 업로드”에서 뭘 배우나요?
API에서 수명이 짧은 사전 서명 URL을 발급해 대용량 업로드를 객체 저장소로 오프로드합니다 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“사전 서명 URL을 사용한 S3 직접 업로드” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Multer 인터셉터를 사용한 멀티파트 업로드
- StreamableFile로 대용량 응답 스트리밍하기
- 사전 서명 URL을 사용한 S3 직접 업로드
- Sharp를 사용한 이미지 처리 파이프라인