Serverless React Web App with AWS Amplify — Part Three

James Hamann
Aug 13, 2018 · 8 min read

Following on from my previous post, Serverless React Web App with AWS Amplify — Part Two, today we’ll be adding authentication and looking at deployment and distribution in the final part of this mini series.

All source code for the project can be found here.

At the moment our app should look somewhat similar to the below, with the ability to add/edit/delete items.

Current App

User Authentication

Let’s start by enabling the user-signin feature using the awsmobile CLI.

#bash$ awsmobile user-signin enable --prompt
? Sign-in is currently disabled, what do you want to do next
Enable sign-in with default settings
#Choose default settings $ awsmobile push #push your changes to the cloud

To keep things simple, we’ll use Amplify’s withAuthenticator component to handle our auth flow. This component wraps our entire app up and renders a complete sign up/sign in UI, which is customisable through the AWS Mobile Hub. If you wish, you can also handle the Sign In/Sign Up process using the Auth component, which gives you greater flexibility of the entire auth flow.

# App.js [...]import { withAuthenticator } from 'aws-amplify-react'[...]export default withAuthenticator(App, true);

After adding the above code to your App.js file, reload your app and it should look something like this. The added true ensures a sign out button is rendered.

Sign In/Sign Up Page

Try going through the Sign Up flow, you’ll notice MFA (multi-factor auth) is enabled by default, so when putting your mobile number in you’ll get a confirmation code to use each time to sign in/sign up. It’s probably overkill for an app like this, but it does improve security. Once going through the flow and signing in with your newly created user account, you should be directed to your app’s home page.

That’s user authentication done! Pretty simple isn’t it? You can also view all users signed up to your app by heading over to the User Pool on Cognito and clicking on Users and Groups. The easiest way to get to your Cognito Pool is to open up the Mobile Hub, head to the User Sign In card and click “Edit in Cognito.”

AWS Mobile Hub, Cognito Pool Settings

Please remember, whenever you make changes in the hub/on the web app, be sure to pull the changes back into your local project. I’ve caused myself so many stupid issues by not doing this and your project gets real messy, real fast and can get out of sync, so make sure your local copy is always in sync with the cloud.

Federated Identity Login

Now we’ve added user auth, but most modern web apps incorporate some form of social login, so let’s add Google Sign-In to ours.

You’ll need to get a google_client_id. It’s fairly straight forward and Google provide easy to follow instructions here. When asked what you’re developing for, choose Web Server and then add the Authorized JavaScript origins as http://localhost:3000. Be sure to keep this tab open for the time being, as we’ll be going back and fourth retrieving the Client ID as well as changing some settings later on.

Next, we’ll need to add our Client ID to our Cognito Pool, this can be done by configuring the user-signin feature, using the awsmobile CLI tool.

#bash → awsmobile user-signin configure? Sign-in is currently enabled, what do you want to do next Go to advance settings
? Which sign-in method you want to configure Google sign-in (currently disabled)
? Google Web App Client ID xxxxYOURCLIENTIDxxxxx.apps.googleusercontent.com
? Google Android Client ID xxxxYOURCLIENTIDxxxxx.apps.googleusercontent.com
? Google iOS Client ID xxxxYOURCLIENTIDxxxxx.apps.googleusercontent.com
$ awsmobile push //don't forget to push your changes, otherwise it won't work.

Finally, we’ll need to tweak our code to include our google_client_id, so that the withAuthenticator component can use it. As long as you restrict the origins from the Google Dev Console, as we did earlier, there isn’t a specific need to hide this ID, so we don’t need to worry about loading environment variables just yet.

The first thing we need to change is in our App.js file. We revert back to exporting the App as it is, not wrapping it in the withAuthenticator component.

#App.js [...]export default App;

Next, in our index.js file, we import App.js and create a new constant named AppWithAuth, which is essentially what we had previously in our App.js file. We then create another constant called federated and set this equal to a JSON config containing our google_client_id. Lastly, we use our constant AppWithAuth within the render function and include our google_client_id from the federated constant we just created.

#index.jsimport App from './App';import { withAuthenticator } from 'aws-amplify-react'const AppWithAuth = withAuthenticator(App, true);const federated = {
google_client_id: 'xxxxxYOURCLIENTIDxxxxxx.apps.googleusercontent.com',
};
ReactDOM.render(<AppWithAuth federated={federated}/>, document.getElementById('root'));
registerServiceWorker();

After reloading your app, you should be able to successfully login using Google!

Our new sign in/sign up up form with Google Sign in Button
After successful Google Login, the user’s name is displayed on the header with a Sign Out button.

The process for adding Facebook/Amazon Logins is pretty much the same, you’d just need to acquire a client ID from their developer dashboard.

That’s it for Authentication! We successfully added a sign in/sign up form and incorporated Google Login. It’s still quite rough around the edges and could do with some styling, but functionality wise it’s pretty much there.

Deployment and Distribution

Let’s make sure people can actually access and use our app by deploying it and distributing it. AWS Amplify includes one simple command that sets everything up for deployment and distribution.

#bash$ awsmobile publishFile sizes after gzip:379.32 KB  build/static/js/main.c1215b8f.js
99.09 KB build/static/css/main.340cfbbb.css
The project was built assuming it is hosted at the server root.
You can control this with the homepage field in your package.json.
For example, add this to build it for GitHub Pages:
"homepage" : "http://myname.github.io/myapp",The build folder is ready to be deployed.
You may serve it with a static server:
yarn global add serve
serve -s build
Find out more about deployment here:http://bit.ly/2vY88KrSuccessful!
your application is published and hosted at:
http://serverlesswebappexam-hosting-mobilehub-1099236211.s3-website.eu-west-2.amazonaws.com
your application is also distributed through aws CloudFront
https://d2x9wan2jbunv.cloudfront.net

This command will build your app and upload the files to a s3 bucket, configured to host static websites. It’ll also go one step further and distribute this through their Global CDN, CloudFront, making your site quicker and easier to access for users all over the world!

Once uploading has finished, you’ll notice two URLS, one is the bucket URL and one is the cloudfront distribution. If you try logging in on either you’ll get this error.

Redirect_URI_Mismatch error — Update the Authorised Origins within the Google Cloud API Settings

This occurs because the request is coming from a domain that hasn’t been approved, so let’s quickly add our new CloudFront URL to the Authorised Javascript origins, in the Google Cloud API Settings.

After adding this and saving, you should be able to login successfully using Google.

As it’s quite simple to do, I thought it’d be useful to finish by showing you how to point your new app to your personal domain, if you have one. In order to do this, you’ll need your domain name in AWS Route 53.

Firstly, we need to configure our Cloudfront Distribution to include our alternate domain name. Open up the CloudFront Dashboard, locate your distribution and update the Alternate Domain Names. I’ll be using the domain serverlessreactexample.jameshamann.com.

You’ll also need to choose Custom SSL Certificate and select the correct certificate for your domain. Setting up a Certificate in AWS Certificate Manager is incredibly easy and straightforward, you can follow the docs here. One thing to note, make sure the certificates you create are stored in US-East (N. Virginia) in order to access them from CloudFront. You can always check what region you’re in by checking the top right of the app bar, next to your name. When you’re all done, hit Yes, Edit. Now we wait, updates to CloudFront distributions can take some time, so take a little break.

Once your changes are deployed, head over to the Route 53 Dashboard and click on your registered domain. Next, click Create Record Set and fill in your URL in the Name field. You’ll then need to change Alias to Yes and copy your CloudFront URL into the Alias Target field.

Hit Create and wait for your changes to go live! The time taken can vary so don’t worry if it’s not instant, go grab a coffee or beer and come back later to check. Don’t forget to add your new domain name to the Authorised Javascript Origins, in your Google Cloud API settings, to ensure Google Login works correctly.

Congrats! You’ve now got a fully functioning, albeit a bit rough looking, Serverless React Web App! Now you have a great foundation to move forward with, allowing you to build, test and deploy your app in nice, quick iterations.

Further Development

There’s quite a few different things you can do to further enhance your app. Here’s a few to help get the ideas bubbling:

  • Adding a CI/CD Pipeline with CircleCI, check one of my previous posts on this topic.
  • Cleaning up the Views, ensuring the Sign out button is rendered on the correct App bar.
  • Adding pictures using Amplify’s storage feature.
  • Porting to Mobile using React Native — this is probably quite complex for now and would require rewriting some sections of the code, but if you’re up for a challenge give it a go!
  • Adding reviews/comments for users to leave on an item
  • Refine UI
  • Incorporate Amplify’s Chatbot feature, making your app a little more interactive

These are just a few ideas, but there’s lots more you can do to further develop and build new features.

All source code for the project can be found here.

As always, thanks for reading, hit 👏 if you like what you read and be sure to follow to keep up to date with future posts.

James Hamann

Written by

Software Developer https://jameshamann.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade