Amplify-js: unknown error with 200 when sign up user

Created on 21 Mar 2018  路  43Comments  路  Source: aws-amplify/amplify-js

I'm using the cognito javascript sdk at a lambda function (i fork the library to support for server side) and when i try to sign up new user with email, the user is created fine in the user pool, however in the callback, it return unknown error with status code 200.

{"code":"UnknownError","name":"UnknownError","statusCode":200,"message":"200"}

userPool.signUp(username, event.password, attributeList, null, function(err, result){
        if (err) {
            callback(null, {
                statusCode: 400,
                body: JSON.stringify({
                    resultMessage: "UNKNOWN_ERROR",
                    resultDescription: err.message
                })
              });
            return;
        }
        cognitoUser = result.user;

        callback(null, {
            "resultDescription": "SUCCESS",
            "resultMessage": "Successfully registered." ,
            "body": result.user
        });
    });
Cognito documentation

Most helpful comment

Hey all,
I was running into this same issue for the past few days. For me, I was getting the error because I had the "Do you want to remember your user's devices" set to "Always". I set it to "No" and that fixed it.
I'm wondering if its because this library is meant for the client-side (I'm using this in a lambda) and with that option enabled, the library is trying to use some browser-specific way of determining the device, but that's just a blind guess.

All 43 comments

Which version of node.js are you using? Did you tried on a WebApp?

Node.js 6.10. This function is executed in lambda. I didn't try in web app.

I get the same error when trying to call cognitoUser.authenticateUser from within AWS Lambda Function (Node.js 4.3 or 6.10) as per Use case 4 in https://github.com/aws/aws-amplify/tree/master/packages/amazon-cognito-identity-js
{
"code": "UnknownError",
"name": "UnknownError",
"statusCode": 200,
"message": "200"
}

@stephen1706 what version of cognito sdk are you using?

@mlabieniec I'm getting the same result, at version 2.0.1

We are checking with the service teams to see if we can identify anything in the logs. Btw how are you dealing with the fetch requests in node? Re: #403

@mlabieniec i fork this library from master branch and add node-fetch as a dependency to solve the fetch problem.

I'm using amazon-cognito-identity-js version 2.0.1.
I needed to add the following to Client.js file of the above package as a workaround to Fetch API error:
var fetch = require('node-fetch');

After that, Fetch API error was resolved, but started seeing the 'UnknownError' with status code 200 on call cognitoUser.authenticateUser

Hey @mlabieniec , I did some more looking into this for my case.
I added in

    onFailure: function (err) {
      console.log(new Error().stack);
    },

To get the stacktrace, and it was as simple as I hadn't implemented the newPasswordRequired function in the callback.
The output was TypeError: callback.newPasswordRequired is not a function.
Maybe this catch in Client.js could be instead refactored as function(err) {...} and return some context with var Error?

@MacMcIrish thank you for that!

@sballa12 have you tried this to see if it returns similarly ?

I get the same error when trying to call cognitoUser.initiateAuth for custom Authentication, with version 2.0.2 (using Runkit)
The Lambda function was executed but it returned :

code: "UnknownError"
message: "200"
name: "UnknownError"
statusCode: 200

Stacktrace error :

    at Object.onFailure (/app/index.js:55:23)
    at /app/available_modules/1521883155000/amazon-cognito-identity-js/lib/CognitoUser.js:759:25
    at /app/available_modules/1521883155000/amazon-cognito-identity-js/lib/Client.js:82:14
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:118:7)

Hey, @wcken84 , for this catch, try doing what I've done above with changing it to

    }).catch(function (err) {
      // Taken from aws-sdk-js/lib/protocol/json.js
      console.log(`error: ${err}`);

If you're lucky (like I was), it may show you the method you need to implement in your callback
Don't forget to change it back after you've finished debugging :)

I got the same error as @wcken84. I used 'amazon-cognito-identity-js' and assigned to 'am_cog_id'. Then called am_cog_id.AuthenticationDetails and others by creating objects. What should I do?
Thanks,
Than

Same error @wcken84 , but on sign in. Very vague and difficult to determine what is wrong...

Hey all,
I was running into this same issue for the past few days. For me, I was getting the error because I had the "Do you want to remember your user's devices" set to "Always". I set it to "No" and that fixed it.
I'm wondering if its because this library is meant for the client-side (I'm using this in a lambda) and with that option enabled, the library is trying to use some browser-specific way of determining the device, but that's just a blind guess.

@scvnathan Thank you so much! This did fix the issue for me. We're also running inside of a lambda. Now, there's still the question of what we need to do to fix remembering devices, but at least I can move forward with my auth flow...

For me, It's because I try to sign in with user/password generated from Admin. So, I add newPasswordRequired callback and problem gone.

```
newPasswordRequired: (userAttributes, requiredAttributes) => {
delete userAttributes.email_verified;

cognitoUser.completeNewPasswordChallenge(
"newPassword",
userAttributes,
this
);
}
`

I'm getting the same issue as @wcken84 on cognitoUser.authenticateUser. Both the following:

code: "UnknownError",
name: "UnknownError",
statusCode: 200,
message: "200"
at Object.onFailure (~\index.js:78:25)
at ~\node_modules\amazon-cognito-identity-js\lib\CognitoUser.js:376:31
at ~\node_modules\amazon-cognito-identity-js\lib\CognitoUser.js:361:22
at ~\node_modules\amazon-cognito-identity-js\lib\Client.js:82:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

I tried @scvnathan's idea of switching to never remember the device, but that's not helped unfortunately. Any ideas?

Fixed it...

I'm new to NodeJS, so not sure if this is how it works, but there was an error in my onSuccess function, which then caused the script to fall into onFailure and return this un-useful error message.

I was trying to also use 'aws-sdk', but hadn't installed or imported it. Not sure if it's the same issue for you @wcken84, but all I did was install+import, and it worked.

Also, if I now turn 'Remember user's device' back on, I'm getting the 'UnknownError' response again, so @scvnathan's fix may well work for some people still!

Fixed with

  1. @scvnathan solution - Turn off Remember user's device in cognito user pool.
  2. @thegamenicorus solution. Added newPasswordRequired callback and it returned the CognitoUserSession with tokens (for user created by admin)

Thanks guys !!! 馃槃

@scvnathan solution of turning off 'Remember user's device' in cognito user pool fixed the issue with cognitoUser.authenticateUser

@mbahar perhaps we can add some of these to a troubleshooting section in the docs?

@mlabieniec Although clear documentation in troubleshooting section would definitely help, I still feel that it would be good to enhance the library code to handle this error gracefully.

I think the reason that this is fixed when you turn off remember devices is that it will stop trying to interrogate the device about its nature. It will look at window.navigator (which in a node environment's equivalent global.navigator will be undefined).

It can be tricked fairly easily by doing this at the start of the node application.

global.navigator = {};

I agree with @sballa12 that enhancing the library to not swallow this error would be the best solution (alongside doc enhancement)

POST https://cognito-idp.ap-south-1.amazonaws.com/ 400 (Bad Request)

Sir, Actually i'm a student sir. Cognito is new to me . When i try the USE CASE 1 (Sign up) it always throw the above error in my browser console . I include two js in my html web page

make this changes on your project:
yarn add node-fetch

and then:
global.fetch = require('node-fetch')

before using AWS Cognito.

Getting same error as few of you had mentioned above during Signup.
Although User Registration is successful.

Error - "Unknown error, the response body from fetch is: undefined"

Tried few suggestions but didn't get rid of this error.

Thanks, Tanveer

Same here. Registration is successful for the user, but signUp is returning "Unknown error, the response body from fetch is: undefined". I'm doing this request from the browser.

I'm getting the same error as @medarz is. My callback in userPool.signUp is getting called twice.. The first is successful. The second one has the error.

Same here. Although Sign up was successful, and also received response like - {"CodeDeliveryDetails":{"AttributeName":"email","DeliveryMedium":"EMAIL","Destination":"s@y.com"},"UserConfirmed":false,"UserSub":"*****"}, but inside the function it's throwing error - {code: "UnknownError", message: "Unknown error, the response body from fetch is: undefined"}.

Using inside ReactJS with amazon-cognito-identity-js v2.0.21

I'm getting this same error using Angular 6. I've tried all of the above and still getting the error.

I am having the same issue as I turned on device registration to Always. However, I can't turn it off as we need to enable this feature. Please let me know if there is any work around.

Anyone working on this issue ? I have tried the provided solutions, but still getting the error message. As @nikhilsinha mentioned the function gets called twice and the second one fails.

I have narrowed down the problem to an async call via Promise - when not using Promise everything works fine

//return new Promise(function(resolve, reject){
    userPool.signUp(login, password, attributeList, null, function(err, result){
        if (err) {
          console.log(`Problem creating user ${JSON.stringify(err)}`);
          //reject(err);
        }
        else{
          console.log(`User successfully created ${JSON.stringify(result)}`)
          cognitoUser = result.user;
          //reslove(cognitoUser);
        }

    });
  //});

@sashokbg I tried with window mock and it's working now.

const WindowMock = require('window-mock');
global.window = {localStorage: WindowMock.localStorage};
global.navigator = () => null;

Same here, using node v8.11.2, signUp is called twice, like this:
User successfully created {"user":{"username":"[email protected]","pool":{}, etc etc }
Problem creating user {"code":"UnknownError","message":"Unknown error, the response body from fetch is: undefined"}

I was having this same issue and finally got it to work with this:

rafachurre's comment on a similar thread led me in the right direction. He mentioned that the 'this' context needed to be passed into the Authentication method. Here is exactly how I had to pass 'this' into the cognitoUser.authenticateUser method to be able to change state after successful login.

This was the critical line for me (inside the button component):
clicked={this.loginHandler.bind(this, this)}

and the following lines in the authenticateUser method:

loginHandler (self) {
 var poolData = { UserPoolId  : UserPoolId,
ClientId : ClientId
};

var authenticationData = {
        Username : username,
        Password : password,
    };

    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

    var userData = {
        Username : username,
        Pool : userPool
    };
    var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            var accessToken = result.getAccessToken().getJwtToken();

            /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer*/
            var idToken = result.idToken.jwtToken;
            console.log('Success');
            self.setState({ isLoggedIn: true });
        },

I also had a similar problem, getting Unknown Error (misspelled as Unkown Error).

I found out that having _any_ kind of error within the userPool.signUp() callback function caused the error to be swallowed by the Cognito JS library.

I also was getting "Unkown error" on signup. In my userPool.signUp onSuccess, I was calling userPool.getCurrentUser().signOut() to sign out a previously signed in user, but this was throwing the Unkown error if there wasn't a user signed in.

This was causing signUp to be called twice, once without an error, and once with the Unkown error.

Removing the signOut() fixed it.

Fixed it...

I'm new to NodeJS, so not sure if this is how it works, but there was an error in my onSuccess function, which then caused the script to fall into onFailure and return this un-useful error message.

I was trying to also use 'aws-sdk', but hadn't installed or imported it. Not sure if it's the same issue for you @wcken84, but all I did was install+import, and it worked.

You Saved My Day. After one days time wasting. Figured out this was also the issue with me. Thanks a lot. Cognito Docs from Amazon are not good. I just copied their code and figured out the issue was with their code. Just commented their code inside onSuccess and it worked like magic.

Regarding the userPool.signUp double call - try to add var before cognitoUser:
var cognitoUser = result.user;

Hey @mlabieniec , I did some more looking into this for my case.
I added in

    onFailure: function (err) {
      console.log(new Error().stack);
    },

To get the stacktrace, and it was as simple as I hadn't implemented the newPasswordRequired function in the callback.
The output was TypeError: callback.newPasswordRequired is not a function.
Maybe this catch in Client.js could be instead refactored as function(err) {...} and return some context with var Error?

Thank you! After implementing newPasswordRequired too, it started working.

NewPasswordRequired doesn't make sense to new users.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

karlmosenbacher picture karlmosenbacher  路  3Comments

epicfaace picture epicfaace  路  3Comments

shinnapatthesix picture shinnapatthesix  路  3Comments

callmekatootie picture callmekatootie  路  3Comments

josoroma picture josoroma  路  3Comments