Error: AWS.CognitoIdentityCredentials does not work as a constructor

Encountering a puzzling issue with a custom-built AWS-SDK. Perhaps it's just a case of me missing the forest for the trees, but it's driving me crazy. Here's what's happening.

I constructed an SDK incorporating all Cognito and DynamoDB services based on core version 2.247.1 as instructed by Amazon here.

When trying to require it in my code using the following snippet:

const AWS = require('../../../../assets/scripts/aws-sdk-2.247.1.js');

Furthermore, I followed the example implementation provided by AWS here.

Thus, I crafted the following code to retrieve a session for a logged-in user:

getUserSession(
        response: ICognitoResponse,
        callback: ( callbackResponse: ICognitoResponse ) => {} ) {

        // Validate the Usersession
        this.cognitoUser.getSession((err: any, session: any) => {
            if (err) {
                response = assign(response, { err });
                callback( response );
                return;
            } else {
                /**
                 * Set the right URL
                 * @type {string}
                 */
                const URL = 'cognito-idp.' +
                    environment.AWS_REGION +
                    '.amazonaws.com/' +
                    environment.USERPOOL_ID;

                /**
                 * Update the Credentials with the current updated URL
                 * @type {AWS.CognitoIdentityCredentials}
                 */
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    /**
                     * your identity pool id here
                     */
                    IdentityPoolId: environment.USERPOOL_ID,
                    Logins: {

                        /**
                         * Change the key below according to the
                         * specific region your user pool is in.
                         */
                        URL: session.getIdToken().getJwtToken(),
                    },
                });
            }
        });
    }

The compilation proceeds without errors, and I can log in successfully. However, immediately after that, I encounter the error:

Uncaught: TypeError: AWS.CognitoIdentityCredentials is not a constructor

If I use the same code with the full JavaScript SDK, which is quite massive, everything works as expected.

Hoping someone can provide some assistance. I've tried various import techniques like import * as AWS, but none have yielded successful results.

Answer №1

Successfully implemented the solution! To start, import the necessary library in the "tg" script located in the "index.html" file. Next, include the following code snippet in the ts-File:

declare var AWS: any

With these steps completed, you can now access and utilize AWS.config and AWS.CognitoIdentityCredentials within an Angular 5 application.

Answer №2

I experienced a similar issue where the error stemmed from importing packages from nested directories (for example,

import { CognitoIdentityCredentials, Config } from 'aws-sdk/some/inner/path';
). .

To resolve this, I eliminated the unnecessary directory path and directly imported from the aws-config module (

import { CognitoIdentityCredentials, Config } from 'aws-sdk'
).

Answer №3

In order to adhere to the object definition in aws-sdk.js, you must substitute

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
with
AWS.AWS.config.credentials = new AWS.AWS.CognitoIdentityCredentials({

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

Issue with Backbone: Unable to access property 'fn' as it is undefined

When I attempt to run the code below, I encounter an error that says "Cannot read property 'fn' of undefined" due to jquery not being found. requirejs.config({ baseUrl: "/static/javascript", paths: { jquery: "vendor/jquery", undersco ...

Transferring data from a parent component to a child component nestled inside a tabpanel of a tabview

In the given scenario, there is a child component nested in a tab panel defined within the parent component. This setup allows for multiple tab panels and consequently multiple instances of the child component being nested in each tab panel. The goal is to ...

MSBUILD encounters numerous JQuery errors when compiling a web project with TypeScript

Currently, I am working on a .net core 3.1 (netcoreapp3.1) razor pages project that includes typescript files and a few javascript files. The project builds perfectly from Visual Studio 2019 (professional) as well as from the command line using MSBuild. H ...

React Functional Component not working properly following package update

After a 4-month hiatus from programming, I decided to update this project using npm but encountered issues with all my stateless functions. interface INotFoundPageContainerProps { history: any; } class NotFoundPag ...

Dealing with the Angular 7 ExpressionChangedAfterItHasBeenCheckedError in combination with NgsScrollReveal

Utilizing ngScrollReveal triggers a re-render with every scroll event. I am invoking a function through the HTML in this manner: <component [alternate]="toggleAlternate()"> The code for toggleAlternate() is as follows: toggleAlternate() { this.a ...

Angular TypeScript Validator for Checking Binary Inputs

When working with TypeScript, I am attempting to validate an input field to only accept binary numbers (0 and 1). Here is my HTML: <div> <input type="text" (keypress) = "binaryValidate($event)"> </div> And here ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...

pyodbc module not found in AWS Lambda

Having trouble connecting my MSSQL database with AWS Lambda and I'm not sure how to install the necessary libraries on Lambda import json import urllib.parse import boto3 import pyodbc def lambda_handler(event,context): s3=boto3.client('s3& ...

The Vitest test is not compatible with PrimeVue3 Dialogs and does not function as intended

I am currently working on a project that involves using PrimeVue components, and the time has come to conduct some tests. Below is the code for the test: import { beforeEach, describe, expect, it } from 'vitest' import type { VueWrapper } from & ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Leveraging two data types for a single variable in Typescript

While transferring js typescript, I encountered a problem. The function below is designed to work with two different types of data, but I am seeing this error: Property 'dateTime' does not exist on type 'Operation | OperationCreated'. ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Component template using Knockout.js and RequireJS for HTML widgets

Trying to implement the widget example for knockout from here. Unfortunately, I am having issues loading the template from an external HTML file using requirejs. ko.components.register('like-or-dislike', { template: { require: &apos ...

What is the best way to search through an array in TypeORM?

I am working on implementing user permissions management using TypeORM with PostgreSQL. The permissions are defined within the user entity in the following column: @Column({ type: 'text', array: true }) permissions: UserPermission[] = []; Th ...

Are you able to turn off the TypeScript rule TS(1345)?

When using valid debugging code like the example below, TypeScript may throw an error ("An expression of type 'void' cannot be tested for truthiness.ts(1345)"): const getFooPlusTwo = (foo) => console.log(foo) || foo + 2; There are various hac ...

An ambient module will not be successfully resolved through a relative import operation

As per the typescript documentation (https://www.typescriptlang.org/docs/handbook/module-resolution.html): A relative import is resolved in relation to the importing file and does not resolve to an ambient module declaration. However, it also states: ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

The ListItemButton's onclick event does not trigger on the initial click when utilizing a custom component as its children

I am having trouble comprehending why this onclick function is influenced by the children and how it operates <ListItemButton onClick={() => onClickResult(q)}> <Typography variant="body1">{highlighted}</Typography> ...

Converting a cast method into a function in Typescript

With some experimenting on WebRTC, I found that the ondatachannel callback takes a function, but I'm wondering if it's possible to use a method of a Typescript class instead. Can someone please assist me with this? export class MainComponent imp ...

Receiving a Typescript error stating "Property '0' does not exist on type X" when incorporating auto-generated GraphQL code into the project

I'm struggling to comprehend how to rectify this typographical error. Here's the snippet of code causing me trouble: <script lang="ts"> import type { PlayerListQuery } from "queries"; export let player: PlayerListQ ...