B2 can easily be configured for use with the AWS SDK for JavaScript V3 thanks to the S3 Compatible API. Below is an example of a sample.js that creates a bucket and uploads a file:
import { S3Client, CreateBucketCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { v4 as uuid } from 'uuid';
// Create an S3 client
//
// You must copy the endpoint from your B2 bucket details
// and set the region to match.
const s3 = new S3Client({
endpoint: 'https://s3.us-west-004.backblazeb2.com',
region: 'us-west-004'
});
// Create a bucket and upload something into it
var bucketName = 'node-sdk-sample-' + uuid();
var keyName = 'hello_world.txt';
try {
await s3.send(new CreateBucketCommand({ Bucket: bucketName }));
await s3.send(new PutObjectCommand({
Bucket: bucketName,
Key: keyName,
Body: 'Hello World!'
}));
console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
} catch (err) {
console.log("Error: ", err);
}
Content of package.json:
{
"dependencies": {
"@aws-sdk/client-s3": "^3.32.0",
"uuid": "^9.0.0"
},
"type": "module"
}
Install the dependencies:
% npm install
added 106 packages, and audited 107 packages in 3s
found 0 vulnerabilities
The AWS SDK for JavaScript can read credentials from the shared credentials file, environment variables, and other mechanisms. See Setting Credentials in Node.js for details.
For example, to use the shared credentials file, you can add credentials to ~/.aws/credentials as a separate profile:
[b2]
aws_access_key_id = your_b2_keyId
aws_secret_access_key = your_b2_appKey
Then run the script as follows.
% AWS_PROFILE=b2 node sample.js
Successfully uploaded data to node-sdk-sample-38cb5413-29c2-46f5-ab2d-4ac4d553f929/hello_world.txt
The S3 Compatible API for Backblaze B2 Cloud Storage allows 1000’s of integrations to work with B2 natively. If you’re new to the S3 Compatible API, please see our Getting Started Guide. If you have any trouble using the AWS SDK for JavaScript V3 with B2, please let us know by emailing us at b2feedback@backblaze.com.
Articles in this section
- Object Lock FAQs
- Delivering Private Backblaze B2 Content Through Cloudflare CDN
- Bunny Integration Quick Start Guide
- Guide for using Fastly Compute @ Edge with Backblaze B2
- SSE Command Line and API Examples
- Does the B2 S3 Compatible API support Pre-Signed URLs?
- How to use Fastly CDN with B2
- Using the AWS SDK for Java (v2) with B2
- How to use the AWS SDK for Python with B2.
- Using the AWS SDK for PHP with Backblaze B2 Cloud Storage