Skip to main content

AWS SDK for JavaScript quickstart

The AWS SDK for JavaScript v3 is the modern modular SDK from AWS — small bundle sizes, tree-shakeable, runs in Node.js, the browser, React Native, and Deno. It works against Filebase by setting two configuration values.

Install

npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

Configure

src/filebase.ts
import { S3Client } from '@aws-sdk/client-s3';

export const s3 = new S3Client({
endpoint: 'https://s3.filebase.io',
region: 'auto',
credentials: {
accessKeyId: process.env.FILEBASE_KEY!,
secretAccessKey: process.env.FILEBASE_SECRET!,
},
});

That's the whole thing. Every other operation uses the AWS-provided commands.

List buckets

import { ListBucketsCommand } from '@aws-sdk/client-s3';

const result = await s3.send(new ListBucketsCommand({}));
console.log(result.Buckets?.map((b) => b.Name));

Create a bucket

import { CreateBucketCommand } from '@aws-sdk/client-s3';

await s3.send(new CreateBucketCommand({ Bucket: 'quickstart-demo' }));

Upload an object

import { PutObjectCommand } from '@aws-sdk/client-s3';
import { readFile } from 'node:fs/promises';

const body = await readFile('hello.txt');

await s3.send(
new PutObjectCommand({
Bucket: 'quickstart-demo',
Key: 'hello.txt',
Body: body,
ContentType: 'text/plain',
}),
);

For large objects, prefer the high-level uploader:

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

const upload = new Upload({
client: s3,
params: {
Bucket: 'quickstart-demo',
Key: 'large-file.bin',
Body: createReadStream('./large-file.bin'),
},
});

upload.on('httpUploadProgress', (p) => console.log(p.loaded, '/', p.total));
await upload.done();

Upload automatically handles multipart upload for files larger than 5 MB. See multipart upload for the lower-level API.

List objects

import { ListObjectsV2Command } from '@aws-sdk/client-s3';

const result = await s3.send(
new ListObjectsV2Command({
Bucket: 'quickstart-demo',
MaxKeys: 100,
}),
);

for (const obj of result.Contents ?? []) {
console.log(obj.Key, obj.Size);
}

Download an object

import { GetObjectCommand } from '@aws-sdk/client-s3';

const { Body } = await s3.send(
new GetObjectCommand({ Bucket: 'quickstart-demo', Key: 'hello.txt' }),
);

const text = await Body!.transformToString();
console.log(text);

Generate a pre-signed URL

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

const url = await getSignedUrl(
s3,
new GetObjectCommand({ Bucket: 'quickstart-demo', Key: 'hello.txt' }),
{ expiresIn: 3600 },
);

console.log(url);

The recipient can GET that URL for the next hour without needing your credentials.

Delete an object

import { DeleteObjectCommand } from '@aws-sdk/client-s3';

await s3.send(
new DeleteObjectCommand({ Bucket: 'quickstart-demo', Key: 'hello.txt' }),
);

What's next