Serverless React Web App with AWS Amplify — Part One

James Hamann
7 min readApr 13, 2018

Having previously posted about Accelerating Mobile Development with AWS Amplify, I thought I’d do the same for the Web, using AWS Amplify, Amazon’s new JavaScript Library for app development.

All source code for the project can be found here.

Before diving in, it’s probably worth understanding, at least at a high level, the architecture behind serverless apps and how they work.

What is a Serverless Application?

High Level Serverless Application Model

This diagram represents, at a high level, the architecture of a serverless application. Our static content (React Web App) is stored in an S3 bucket served up to the client, either from CloudFront or directly. This communicates with API Gateway. From here this triggers a Lambda function (which handles all our back end logic) and communicates with DynamoDB to get, save, delete or whatever depending on what request was sent from the client.

What are the benefits?

Cost. You only pay for the compute time you use. This works great if you have large fluctuations in traffic/requests. It also takes the hassle of maintaining a server away and some what simplifies things so you can focus on building your product. Obviously, every app has it’s own requirements and serverless architecture may not fit in all cases, but for the most part it provides a good framework to deploy applications at low cost, with minimal configuration.

What we’ll be building

To keep things nice and simple, and to avoid the stale recycled todo example, we’ll build an online inventory with basic CRUD functions. I’m sure it goes without saying but you’d need an AWS Account, which you can get get here. I’d also advise you to keep an eye on your billing statement so you don’t incur any unexpected charges.

Getting Started

Firstly, we’ll need to install the awsmobile-cli and configure it with our AWS Keys.

#bash$ npm install -g awsmobile-cli
[...]

$ awsmobile configure
$ configure aws
? accessKeyId: [ENTER YOUR ACCESS KEY ID] #hit enter
? secretAccessKey: [ENTER YOUR SECRET ACCESS KEY] #hit enter
? region: eu-west-2 #select your region using arrows and hit enter

Next, we’ll use create-react-app to scaffold up a React App for us.

#bash $ create-react-app serverless-web-app-example
[...]
✨ Done in 17.74s.
Success! Created serverless-web-app-example at /Users/jameshamann/Documents/Development/serverless-web-app-example
Inside that directory, you can run several commands:
yarn start
Starts the development server.
yarn build
Bundles the app into static files for production.
yarn test
Starts the test runner.
yarn eject
Removes this tool and copies build dependencies, configuration files
and scripts into the app directory. If you do this, you can’t go back!
We suggest that you begin by typing:cd serverless-web-app-example
yarn start
Happy hacking!
$ cd serverless-web-app-example

Let’s fire up our app to make sure it’s all setup correctly.

React Starter Page

Great, looks good! Now lets install aws-amplify and aws-amplify-react (which just contains helpers and higher order components for react) within our project.

#bash $ npm install aws-amplify --save 
[...]
$ npm install aws-amplify-react --save
[...]

Once this is all installed, we’ll need to setup our backend. To initialise a project, we use the awsmobile init command within the root of our project. You’ll be prompted a few questions, usually the default answers provided are correct so you should be able to hit enter for each of them.

#bash $ awsmobile init
[...]
✨ Done in 5.30s.
yarn add aws-amplify-react returned 0
Success! your project is now initialized with awsmobilejsawsmobilejs/.awsmobile
is the workspace of awsmobile-cli, please do not modify its contents
awsmobilejs/#current-backend-info
contains information of the backend awsmobile project from the last
synchronization with the cloud
awsmobilejs/backend
is where you develop the codebase of the backend awsmobile project
awsmobile console
opens the web console of the backend awsmobile project
awsmobile run
pushes the latest development of the backend awsmobile project to the cloud,
and runs the frontend application locally
awsmobile publish
pushes the latest development of the backend awsmobile project to the cloud,
and publishes the frontend application to aws S3 for hosting
Happy coding with awsmobile!

This command creates all the necessary resources in AWS for your backend, as well as creating a awsmobilejs folder within the root of your project, which contains basic information about your project.

Lastly, we’ll need to hook up our client (React app) to our newly created backend. In your app’s entry point (usually App.js) include the bolded code in the snippet. This just imports the Amplify Library and configures it using a file called aws_exports which is generated when you initialise your backend, in the previous step.

# App.js import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Amplify from 'aws-amplify';
import aws_exports from './aws-exports';
Amplify.configure(aws_exports);class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;

Lambda and API Setup

Now we’ve got the basic infrastructure setup, let’s setup Lambda, API Gateway and DynamoDB for our basic CRUD functions. To do this, run the awsmobile features command. From here, you can see what features you’re able to activate and what features are available as default. For now we only require cloud-api and database to be selected and activated.

#bash awsmobile features? select features:
◯ user-signin
◯ user-files
◉ cloud-api
❯◉ database
◉ analytics
◉ hosting
# hit space to select the features you'd like and enter to confirm

Whenever you change something locally, as we’ve just done, we’ll need to push it to AWS so the changes can take effect.

#bash$ awsmobile push

Once everything’s been initialised and pushed, have a poke around the backend directory, within awsmobilejs. There should be a cloud-api directory that contains your Lambda Project and a bunch of boilerplate code to get you started. By default, Lambda is setup to use AWS’s Serverless Express Framework for Node.js, so if you’re experienced with Node.js and Express, everything should look pretty familiar.

At this point, I like to do a quick check to make sure the Client and Backend are setup and talking to each other. To do this, I write a get request within the componentDidMount function, so as soon as our Component mounts, it fetches data from our backend and logs it to the console. AWS Amplify provides a component, API, to handle all requests to our backend.

# App.jsimport React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Amplify, { API } from 'aws-amplify';
import aws_exports from './aws-exports';
Amplify.configure(aws_exports);let apiName = 'sampleCloudApi';
let path = '/items';
class App extends Component {componentDidMount(){
API.get(apiName, path).then(response => {
console.log(response)
});
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;

If you’ve poked around the Lambda app.js file, you’ll notice we should be expecting a response of ({success: ‘get call succeed!’, url: req.url}).

Ok, you might need to squint, but if you check the console you’ll see our request object {success: “get call succeeded!”, url: /items”}. Great! Everything’s hooked up and ready to go.

In the next part we’ll look at setting our Front End Pages up and creating the basic CRUD Functions.

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.

Serverless React Web App with AWS Amplify — Part Two Available Here

📝 Read this story later in Journal.

🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >

--

--