Setting up NodeJS with Contabo Object Storage

Contabo just launched their Object-Storage (https://contabo.com/en/object-storage/) today, providing a very solid pricing for a S3-like storage-system.

Pricing taken from contabo.com

Setup with NodeJS

To use the Contabo-Storage with NodeJS you can use the official aws-sdk (https://www.npmjs.com/package/aws-sdk) for development.

To authenticate against the contabo object storage you need configure some things to work:

// Import aws-sdk
const AWS = require("aws-sdk");
// Enter copied access KEY and secret key here
const ID = "<ACCESS-KEY>";
const SECRET = "<SECRET-KEY>";

The access and secret key can be taken from the Contabo Object Storage Web-Panel (Account > Security & Access > S3 Object Storage Credentials)

Now let’s access S3:

const s3 = new AWS.S3({
  accessKeyId: ID,
  secretAccessKey: SECRET,
  region: "",
  endpoint: "https://eu2.contabostorage.com",
  s3BucketEndpoint: true,
  s3ForcePathStyle: true,
});

The endpoint can be seen in the Bucket URL in the Contabo Object Storage Web-Panel (Storage > Object Storage > Bucket URL). You should not add the bucket name in the endpoint value though (only the base URL).

Then you only need to define the Bucket to access and can perform operations as usual with aws-S3:

// The name of the bucket that you want to access
const BUCKET_NAME = "test";

// Example of uploading a file
const uploadFile = (fileName) => {
  // Read content from the file
  const fileContent = fs.readFileSync(fileName);

  // Setting up S3 upload parameters
  const params = {
    Bucket: BUCKET_NAME,
    Key: fileName, // File name you want to save as in S3
    Body: fileContent,
  };

  // Uploading files to the bucket
  s3.upload(params, function (err, data) {
    if (err) {
      throw err;
    }
    console.log(`File uploaded successfully. ${data.Location}`);
  });
};

// Upload ./test.txt to the bucket
uploadFile("test.txt");

Leave a Reply