The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3:

When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating

The AWS Access Key Id you provided does not exist in our records.

Initially, I believed the problem was due to incorrect usage of AWS_ACCESS_KEY_ID. However, adding a specific line of code right after initializing the client resolved the error and correctly logged the values:

s3.config.credentials().then(console.log)

What puzzles me is that if I call this line within an asynchronous function or at any other point in the code, it no longer resolves the issue.

  • Why does calling this async function resolve subsequent executions?
  • Does it only temporarily fix the client, which remains instantiated for multiple function calls?
  • Could the promise be getting resolved too late – after the initial client call?
  • Why doesn't it work when called just before an s3 call (with or without await)?

Here's the relevant portion of my code:

const s3Config: S3ClientConfig = {}
s3Config.endpoint = new HttpRequest({...} as Endpoint) // used with a local s3 server
const s3 = new S3Client(s3Config);

// Workaround solution
s3.config.credentials().then(console.log)

export const upload = async (...) => {
    // Issue observed here
    // await s3.config.credentials().then(console.log)

    const streamUpload = new Upload({client: s3,...})
    return await streamUpload.done()
}


export const getTempLink = async (...) => {
    // Issue observed here
    // await s3.config.credentials().then(console.log)

    //* Get the pre-signed url
    const command = new GetObjectCommand({Bucket,Key})
    return await getSignedUrl(s3 as any, command as any, { expiresIn })
}

Thank you for your assistance!

Answer №1

I encountered a similar issue recently

The main issue was differentiating between aws-sdk and aws-sdk/client-s3

Upon investigating, I realized that the key names in the .env file were causing the problem:

ACCESS_KEY_ID,
SECRET_ACCESS_KEY,
AWS_SESSION_TOKEN

After making the necessary changes to the key names as shown below, everything started working smoothly with the credentials being recognized:

AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_SESSION_TOKEN,

It's important to keep in mind that AWS follows a chain of precedence for credentials

Answer №2

I have discovered some key information that helped me find answers to my questions:

Referencing the line in question, the code snippet that makes it work is

await s3.config.credentials()

What is the significance of this async function call in resolving the rest of the execution?

In response to this query, it was explained here that utilizing service constructors allows for multiple AWS configurations. Furthermore, as noted by Programmer89, the order of precedence matters, with a caveat:
AWS clients do not load the configuration immediately, but only when required.

By using the config.credentials() function, the configuration is loaded promptly.

Why does it not work when invoked just before an s3 call (with or without await)?

This configuration must be loaded immediately due to the usage of the same AWS SDK with other configurations (utilizing custom DynamoDB and S3 endpoints for local testing).

If called after any point, it appears to utilize the last environment variable used with that SDK rather than the one available at the time of constructor invocation.

Does this solely resolve the client temporarily? (the client remains instantiated for multiple function calls)

While uncertain, it may or may not, but this issue was observed only during local testing.

In production, these processes are better segregated. The client does not persist beyond a single call locally, hence no further investigation was conducted.

Is there a risk of the Promise resolving too late: subsequent to the initial client call?

It appears inconsequential as long as the client initiates loading the configuration (i.e., the Promise commences).

I trust that the insights gathered here could aid others facing similar challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the state changes, initiate the animation

Currently, I am working with Vue.js and need to animate a navigation menu. My goal is to display two li elements when a user hovers over one of the navigation buttons. At the moment, I have set the data type showActivities to false by default and changed ...

Populate a map<object, string> with values from an Angular 6 form

I'm currently setting keys and values into a map from a form, checking for validation if the field is not null for each one. I am seeking a more efficient solution to streamline my code as I have over 10 fields to handle... Below is an excerpt of my ...

AngularJS view does not wait for the completion of $http.get request

Within my controller, the code snippet below is present... $scope.products = dataService.getJsonData(); console.log($scope.products); The corresponding code in my dataservice is as follows: .service('dataService', function ($http) { t ...

Vite encounters issues when using PNPM because of import analysis on the `node_modules/.pnpm` package

When utilizing PNPM and Vite in a monorepo, I encountered a perplexing issue. The email addresses appearing like `<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6a9b4a580f4eef4eef9">[email protected]</a>_@<a ...

Adjusting speed dynamically within a setInterval function in JavaScript

I am working on a react application that requires displaying text with varying intervals between sentences, one at a time. To achieve this functionality, I stored all the sentences in an array and implemented a setInterval function: startShowingText() ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

Choose up to three elements using jQuery

DEMO I'm currently working on a project where I need to select only 3 items at a time. However, all the elements are being selected instead. Can someone please provide guidance on how to achieve this? "If a user wants to select another element, th ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

What is the best way to use JavaScript to click on a block and retrieve its attribute value?

Struggling to capture the data-id attribute value of each item on click, despite researching online. Seeking guidance as I navigate the learning process and encounter programming frustrations. document.addEventListener("click", handle); const demo = e. ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Reading cached JSON value in a Node.js application

Recently, I embarked on creating a node.js application and reached a stage where I needed to retrieve a value from an updated JSON file. However, my attempts using the 'sleep' module to introduce a small delay were unsuccessful. I'm relativ ...

jQuery Show/Hide Not Working Properly

I'm attempting to showcase one Tweet at a time and have it rotate through different tweets. I'm facing an issue where it works correctly on one type of page, but not on the other. Could this be due to a CSS precedence rule overriding the function ...

Identifying Gmail line breaks in the clipboard using Angular

I'm currently working on a feature that allows users to paste content from Gmail into a field and detect line breaks. The field doesn't have to be a text area, I just need to identify the line breaks. However, there seems to be an issue with det ...

Material UI: Dynamic font scaling based on screen size

If I were to adjust the font size responsively in Tailwind, here's how it would look: <div className="text-xl sm:text-4xl">Hello World</div> When working with Material UI, Typography is used for setting text sizes responsively. ...

Utilizing HTML and JavaScript to add grayscale effect to images within a table, with the ability to revert to the colored version upon mouseover

Seeking advice on utilizing the mouseover / mouseout event in javascript to implement grayscale on a table. The challenge requires creating a gray image grid (table) using HTML and then incorporating Javascript so that hovering over an image triggers it to ...

"Creating an array object in the state of Reactjs - a step-by-step

As I am delving into the world of ReactJS, I am learning about changing state within this framework. One challenge I encountered was initializing an array object in state with an unknown length and updating it later using setState. Let me share the snippet ...

Are there any disadvantages to utilizing bindActionCreators within the constructor of a React component when using Redux?

I have come across numerous instances where the bindActionCreators function is used within the mapDispatchToProps function as shown below: ... const mapDispatchToProps = (dispatch, props) => ({ actions: bindActionCreators({ doSomething: som ...

Next.js TypeScript throws an error stating that the object 'window' is not defined

When trying to declare an audio context, I encountered an error stating that window is undefined. I attempted declaring declare const window :any above window.Context, but the issue persists. Does anyone have a solution for this problem? window.AudioCont ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...