import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"; export default defineEventHandler(async (event) => { const key = getRouterParam(event, 'key'); if (!key) { throw createError({ statusCode: 400, statusMessage: 'Missing file key' }); } const config = useRuntimeConfig(); const s3 = new S3Client({ region: config.s3.region || 'us-east-1', endpoint: config.s3.endpoint!, credentials: { accessKeyId: config.s3.accessKeyId!, secretAccessKey: config.s3.secret!, }, forcePathStyle: true, }); try { const response = await s3.send(new GetObjectCommand({ Bucket: config.s3.bucket!, Key: key, })); // 3. Set the correct headers so the browser knows what it's receiving setHeaders(event, { 'Content-Type': response.ContentType || 'application/octet-stream', 'Content-Length': response.ContentLength?.toString() || '', 'Cache-Control': 'public, max-age=3600', // Optional: cache for 1 hour }); // 4. Return the body as a stream directly to the client return response.Body; } catch (error: any) { if (error.name === 'NoSuchKey') { throw createError({ statusCode: 404, statusMessage: 'File not found' }); } throw createError({ statusCode: 500, statusMessage: 'Error fetching file' }); } });