type error for fetch while using aws-cognito-identity-js

Viewed 1105

I am building an serverless a app using the serverless framework and typescript and using aws cognito for user authentication. When I am using the application in local serverless environment everything works. I can sign up a user and also sign the user in to recieve jwt token

But when I deploy the code to aws it gives me "message": "fetch is not a function",

So i go through different github issues / stack overflow and see that everyone suggests the similar solution by adding global.fetch Similar solution in this post -> Nuxt application with amazon-cognito-identity-js package gives error fetch is not defined

global.fetch = require('node-fetch')
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');

so I added the above and did an npm install of node-fetch and pushed the code but then the problem is different, which is that since I am using typescript i can't use global.fetch

So i find different ways to change that in local

Way 1 
const globalAny:any = global;
globalAny.fetch = require('node-fetch');

Way 2
(global as any).fetch = require('node-fetch');

Way 3 -> Written at the end of this post. https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined

And when I run it in both ways in local and also in AWS LAMDA it fails with the same error

TypeError: fetch is not a function

So I am out of options and looking if someone can help me out.

2 Answers

if webpack is used in the project, global.fetch won't work. Add following library in app root level.( recommended for serverless-webpack / any other web pack for lambda codestart )

require('cross-fetch/polyfill');
Related