Busca en todas las páginas de la documentación
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner// lib/s3.ts
import { S3Client } from "@aws-sdk/client-s3";
export const s3Client = new S3Client({
region: process.env.AWS_REGION!,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
},
});// app/api/upload/route.ts
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { s3Client } from "@/lib/s3";
export async function POST(req: Request) {
const { filename, contentType } = await req.json();
const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET_NAME!,
Key: `uploads/${Date.now()}-${filename}`,
ContentType: contentType,
});
const url = await getSignedUrl(s3Client, command, { expiresIn: 600 });
return Response.json({ url });
}Cuándo usarlo: Necesitas cargar, descargar o administrar archivos en Amazon S3 desde una aplicación Next.js, usando URLs presignadas para cargas seguras del lado del cliente.
// app/components/FileUploader.tsx
"use client";
import { useState, useRef } from "react";
export default function FileUploader() {
const [uploading, setUploading] = useState(false);
const [uploadedUrl, setUploadedUrl] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
async function handleUpload() {
const file = fileInputRef.current?.files?.[0];
if (!file) return;
setUploading(true);
try {
// Paso 1: Obtén la URL presignada de nuestra API
const res = await fetch("/api/upload", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});
const { url } = await res.json();
// Paso 2: Carga directamente a S3 usando la URL presignada
await fetch(url, {
method: "PUT",
headers: { "Content-Type": file.type },
body: file,
});
// Extrae la URL permanente (sin parámetros de consulta)
const permanentUrl = url.split("?")[0];
setUploadedUrl(permanentUrl);
} catch (error) {
console.error("La carga falló:", error);
} finally {
setUploading(false);
}
}
return (
<div className="p-6 max-w-md mx-auto space-y-4">
<div>
<input
ref={fileInputRef}
type="file"
accept="image/*,.pdf,.doc,.docx"
className="block w-full text-sm"
/>
</div>
<button
onClick={handleUpload}
disabled={uploading}
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
>
{uploading ? "Cargando..." : "Cargar"}
</button>
{uploadedUrl && (
<p className="text-sm text-green-600">
Cargado: <a href={uploadedUrl} className="underline">Ver archivo</a>
</p>
)}
</div>
);
}// app/actions/s3-actions.ts
"use server";
import {
ListObjectsV2Command,
GetObjectCommand,
DeleteObjectCommand,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { s3Client } from "@/lib/s3";
const BUCKET = process.env.S3_BUCKET_NAME!;
export async function listFiles(prefix: string = "uploads/") {
const command = new ListObjectsV2Command({
Bucket: BUCKET,
Prefix: prefix,
MaxKeys: 50,
});
const response = await s3Client.send(command);
return (
response.Contents?.map((item) => ({
key: item.Key!,
size: item.Size!,
lastModified: item.LastModified!.toISOString(),
})) ?? []
);
}
export async function getDownloadUrl(key: string) {
const command = new GetObjectCommand({
Bucket: BUCKET,
Key: key,
});
return getSignedUrl(s3Client, command, { expiresIn: 3600 });
}
export async function deleteFile(key: string) {
const command = new DeleteObjectCommand({
Bucket: BUCKET,
Key: key,
});
await s3Client.send(command);
}Lo que esto demuestra:
@aws-sdk/client-s3)send() a través del cliente@aws-sdk/s3-request-presigner genera URLs firmadas con límite de tiempo para cualquier comando de S3/ como delimitador, pero S3 es almacenamiento plano - las carpetas son solo prefijos de claveCarga de archivo de Server Action (para archivos más pequeños):
"use server";
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "@/lib/s3";
export async function uploadFile(formData: FormData) {
const file = formData.get("file") as File;
const buffer = Buffer.from(await file.arrayBuffer());
const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET_NAME!,
Key: `uploads/${Date.now()}-${file.name}`,
Body: buffer,
ContentType: file.type,
});
await s3Client.send(command);
}Descarga y transmisión de un archivo:
// app/api/download/[key]/route.ts
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "@/lib/s3";
export async function GET(
req: Request,
{ params }: { params: { key: string } }
) {
const command = new GetObjectCommand({
Bucket: process.env.S3_BUCKET_NAME!,
Key: decodeURIComponent(params.key),
});
const response = await s3Client.send(command);
const stream = response.Body as ReadableStream;
return new Response(stream, {
headers: {
"Content-Type": response.ContentType ?? "application/octet-stream",
"Content-Length": String(response.ContentLength),
},
});
}Copiar objetos entre buckets:
import { CopyObjectCommand } from "@aws-sdk/client-s3";
const command = new CopyObjectCommand({
Bucket: "destination-bucket",
CopySource: "source-bucket/path/to/file.pdf",
Key: "new-path/file.pdf",
});
await s3Client.send(command);PutObjectCommandInput, GetObjectCommandInput, etc.GetObjectCommandOutput.Body está tipado como StreamingBlobPayloadOutputTypes - convierte a ReadableStream en entornos sin servidorS3ClientConfig para configuración personalizada del clienteimport type {
PutObjectCommandInput,
ListObjectsV2CommandOutput,
} from "@aws-sdk/client-s3";
const params: PutObjectCommandInput = {
Bucket: "my-bucket",
Key: "file.txt",
Body: "Hello, World!",
};Errores de CORS en carga del lado del cliente - El navegador bloquea las solicitudes PUT a S3. Solución: Configura CORS en el bucket de S3 para permitir PUT desde tu dominio. Añade AllowedOrigins, AllowedMethods: ["PUT"] y AllowedHeaders: ["Content-Type"].
URL presignada expirada - Las URLs expiran después de los segundos configurados en expiresIn. Solución: Genera URLs justo antes de usarlas. Por defecto, 600 segundos (10 minutos) para cargas; no generes URLs con mucha anticipación.
Cargas de archivos grandes fallando - Los archivos de más de 5 GB no pueden usar PUT único. Solución: Usa carga multiparte con la clase Upload de @aws-sdk/lib-storage para archivos superiores a 100 MB.
Content-Type faltante - Los archivos cargados sin Content-Type obtienen application/octet-stream. Solución: Siempre pasa ContentType en PutObjectCommand y en los encabezados fetch del lado del cliente.
Límite de tamaño del body de Next.js - Las cargas de Server Action están limitadas al límite de tamaño del body de Next.js (por defecto 1 MB). Solución: Usa cargas de URL presignada para archivos más grandes o aumenta experimental.serverActions.bodySizeLimit en next.config.js.
Exposición de credenciales - Nunca importes @aws-sdk/client-s3 en componentes de cliente. Solución: Todo el uso de AWS SDK debe estar en rutas de API, Server Components o Server Actions.
| Librería | Mejor para | Compensación |
|---|---|---|
| @aws-sdk/client-s3 | Acceso completo a la API de S3 | Requiere cuenta de AWS y configuración de CORS |
| Vercel Blob | Almacenamiento simple de archivos en Vercel | Solo Vercel, menos control |
| Uploadthing | Cargas de archivos con hooks de React | Abstracción sobre S3, menos flexibilidad |
| Cloudflare R2 | Compatible con S3, sin cuotas de salida | SDK separado o modo de compatibilidad S3 |
| Supabase Storage | Integrado con Supabase | Ligado al ecosistema de Supabase |
getSignedUrl y la devuelvefetch(url, { method: "PUT", body: file }) para cargar directamente a S3PUT desde tu dominioAllowedHeaders: ["Content-Type"] y tu dominio en AllowedOriginsPutObjectCommand único está limitado a 5 GB@aws-sdk/lib-storage y su clase Upload para cargas multiparteexperimental.serverActions.bodySizeLimit en next.config.jsconst command = new GetObjectCommand({ Bucket: BUCKET, Key: key });
const response = await s3Client.send(command);
return new Response(response.Body as ReadableStream, {
headers: {
"Content-Type": response.ContentType ?? "application/octet-stream",
"Content-Length": String(response.ContentLength),
},
});ContentType en PutObjectCommand, S3 por defecto usa application/octet-streamContentType: file.type tanto en el comando como en los encabezados fetch del lado del clienteimport type { PutObjectCommandInput } from "@aws-sdk/client-s3";
const params: PutObjectCommandInput = {
Bucket: "my-bucket",
Key: "file.txt",
Body: "Hello, World!",
ContentType: "text/plain",
};Cada comando tiene un tipo *CommandInput y *CommandOutput correspondiente.
Body está tipado como StreamingBlobPayloadOutputTypes, no como ReadableStreamresponse.Body as ReadableStreamundefined antes de usar el bodyconst command = new ListObjectsV2Command({
Bucket: BUCKET,
Prefix: "uploads/images/",
MaxKeys: 50,
});
const response = await s3Client.send(command);
const files = response.Contents ?? [];S3 es almacenamiento plano -- las "carpetas" son solo prefijos de clave separados por /.
"use server";
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "@/lib/s3";
export async function deleteFile(key: string) {
await s3Client.send(
new DeleteObjectCommand({ Bucket: BUCKET, Key: key })
);
}Revisado por Chris St. John·Última actualización: 16 jul 2026
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥