Skip to main content

🟨 Node.js (AWS SDK v3)

Install the S3 client: npm install @aws-sdk/client-s3 (add @aws-sdk/s3-request-presigner and @aws-sdk/lib-storage for presigning and managed multipart uploads).

Setup

import { S3Client, CreateBucketCommand, PutObjectCommand,
GetObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3'

const s3 = new S3Client({
endpoint: 'https://s3.lighthouse.storage',
region: 'us-east-1',
credentials: {
accessKeyId: process.env.LH_S3_ACCESS_KEY,
secretAccessKey: process.env.LH_S3_SECRET_KEY,
},
forcePathStyle: true,
})

Upload

import { readFile } from 'node:fs/promises'

await s3.send(new CreateBucketCommand({ Bucket: 'my-app-data' }))

await s3.send(new PutObjectCommand({
Bucket: 'my-app-data',
Key: 'avatars/user-1.png',
Body: await readFile('avatar.png'),
ContentType: 'image/png',
Metadata: { owner: 'alice' },
}))

For large files or streams, use the managed uploader (automatic multipart):

import { Upload } from '@aws-sdk/lib-storage'
import { createReadStream } from 'node:fs'

await new Upload({
client: s3,
params: {
Bucket: 'my-app-data',
Key: 'videos/demo.mp4',
Body: createReadStream('demo.mp4'),
ContentType: 'video/mp4',
},
}).done()

Get the CID

const head = await s3.send(new HeadObjectCommand({
Bucket: 'my-app-data', Key: 'avatars/user-1.png',
}))
console.log(head.Metadata.cid)

Download and presign

import { getSignedUrl } from '@aws-sdk/s3-request-presigner'

// download
const obj = await s3.send(new GetObjectCommand({ Bucket: 'my-app-data', Key: 'avatars/user-1.png' }))
const bytes = await obj.Body.transformToByteArray()

// presigned URL, valid 1 hour
const url = await getSignedUrl(s3,
new GetObjectCommand({ Bucket: 'my-app-data', Key: 'avatars/user-1.png' }),
{ expiresIn: 3600 })