Handling validation errors from API-Gateway with AWS Amplify using ReactJs

Posted on April 11, 2018

Recently, I’ve been working with AWS in order to experience how it is to build a MVP really quickly. The goal I’ve been trying to achieve is to use as much AWS tools as possible to get a working product in production the fastest.

To do that, I choose to rely on :

Lambda for back-end code

API-Gateway for REST API

DynamoDB as a database

Cognito to manage Singnin / Singup and authenticated calls to the API.

Once Cognito configured and a user created, I’ve been able to create a login form quite easily following the server-stack tutorial.

Then, I’ve started protecting my API-Gateway endpoints with an IAM role in order to make some of them only reachable for logged users.

By doing this, I needed to start making my http calls authenticated… this is where things started to mess.

Make an authenticated call when working with Cognito and API-Gateway means using a JWT retrieved from the authorizer (the IAM role here). But this token must be signed.

AWS used to recommend their Javascript SDK to do that. But the procedure is quite complicated. We need to use at least 3 different libs to do the job (here is an example). To fix that and make things easier for developers, Amazon shipped a React lib called aws-amplify : https://github.com/aws/aws-amplify.

Amplify may be seen as a unification of those 3 libs (including the AWS JS SDK) thought to make developer life easier.

Because Amplify use Axios, when API-Gateway returns a 400 status code, the error is thrown and if you want to use the returned payload you need to access the err.response.data object (see this issue). But this is not so obvious and more over, there is no example of error handling in the aws-amplify documentation.