Use the AWS SDK for JavaScript V3 with Backblaze B2
    • Dark
      Light

    Use the AWS SDK for JavaScript V3 with Backblaze B2

    • Dark
      Light

    Article Summary

    You can easily configure Backblaze B2 Cloud Storage for use the AWS SDK for JavaScript V3 using the S3-Compatible API.

    The following example shows 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);
    }

    The following code sample shows the content of config.json:

    {
      "dependencies": {
        "@aws-sdk/client-s3": "^3.32.0",
        "uuid": "^9.0.0"
      },
      "type": "module"
    }

    The following code sample shows how to install 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, 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 following script:

    % 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 allows 1000’s of integrations to natively work with Backblaze B2. If you are new to the S3-Compatible API, click here. If you have issues using this SDK with Backblaze B2, let us know by emailing us at [email protected].


    Was this article helpful?