I am using AWS Cognito to user user pools and authentication.
My registration is working but my login function is throwing an error:
/node_modules/aws-sdk/lib/request.js:31 throw err; ^
ReferenceError: window is not defined
Here is the function:
app.post('/login', function(req, res, next) {
console.log("Email: " + req.body.email);
console.log("Password: " + req.body.password);
var authenticationData = {
Username: req.body.username,
Password: req.body.password
};
var authenticationDetails = new AWS.CognitoIdentityServiceProvider
.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId: '*removed for security*',
ClientId: '*removed for security*'
};
var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(
poolData);
var userData = {
Username: req.body.username,
Pool: userPool
};
var cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(
userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: '*removed for security*',
Logins: {
'*removed for security*': result
.getIdToken().getJwtToken()
}
});
},
onSuccess: function(suc) {
console.log('Login Successful!');
},
onFailure: function(err) {
console.log('Login Unsuccessful');
alert(err);
},
});
});
I'm pretty sure the error is occuring during execution of the following line as I placed debug logs throughout the code and it only executed up till here:
var cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData);
AWS Cognito JS SDK is meant to be used on the client's side. If you wish to use it on the server side, you can mock the window object using window-mock
library for example.
npm install --save window-mock
Then, on top of the file and before your function, add the following:
import WindowMock from 'window-mock';
global.window = {localStorage: new WindowMock().localStorage};
After this, you're gonna get navigator not defined
error, which you can solve with:
global.navigator = () => null;
Then you should be able to print the result on either of the callbacks.
I observed this issue to occur while running in NodeJS only when you enable "remember your user's devices" in user pool. If I disable the same, the error does not occur. It does make sense because as Sam mentioned, it is meant to be used on client side and since running from server side will not have these browser properites. I was getting similar related error "ReferenceError: navigator is not defined".
Set No in all device management sections, if you are running in nodejs and you dont want any Device to be remembered. CogintoUser API tries to get UserAgent from the Device and assumes navigator as the Device.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With