Protected Routes with AWS Amplify using React context

Question:

I am migrating an app from Firebase to AWS Amplify. I want to create a React context which will provide route protection if the user is not logged in.

For example, my Auth.js file:

And my App.js file:

This all works fine.

How would I do something similar with AWS Amplify? Essentially how would I create a Auth.js file that would wrap around my routes and give them a user context (which would update when the authentication status for the user is changed).

Thanks!

Answer:

You can achieve this by setting up a custom protectedRoute HOC that will be used to protect any route that requires authentication. It will check if the user is signed-in and if the user is not signed-in then it will re-direct them to a specified route.

protectedRoute.js

You can specify the default route or another route like the following:

You could also use the pre-built HOC from aws-amplify called withAuthenticator and that provides the UI as well as checking the users authentication status.

Sample use case for a profile page:

The routing for both would be the same and below I have linked a sample that I have used for both.:

Leave a Reply