Search code examples
javascriptamazon-web-servicesamazon-s3amazon-javascript-sdk

Is this the correct way to use the AWS global config in the JavaScript SDK?


The way AWS gets configured strikes me as really odd. You can apparently set the config in one file, and then you don't have to export the configured AWS object, you can just import it straight from node modules again. I'm having a hard time understanding how/why this works:

// config.js
const AWS = require('aws-sdk')
AWS.config.update({ region: 'us-east-2', signatureVersion: 'v4' })

Then in some other file, I can just import AWS like this, and the config magically sticks with it:

// some other js file
const AWS = require('aws-sdk') // look, I didn't import this from config.js!
const s3 = new AWS.S3() // it knows how to use the right region & signature!

Why shouldn't I export the AWS that I configured and import that instead? How is the configuration copied over even when I'm not importing it from my config file?


Solution

  • If you take a look at the source code you can see that the AWS object has config a property which is initialized.

    This is essentially singleton object, it relies on module caching in Node.js.

    From the NodeJS docs:

    Caching

    Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

    Provided require.cache is not modified, multiple calls to require('foo') will not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

    To have a module execute code multiple times, export a function, and call that function.