| layout | example |
|---|---|
| title | How to create a React.js app with serverless |
| short_title | React.js |
| date | 2021-06-16 17:00:00 -0700 |
| lang | en |
| index | 1 |
| type | webapp |
| description | In this example we will look at how to use React.js with a serverless API to create a simple click counter app. We'll be using SST and the ReactStaticSite construct to deploy our app to AWS S3 and CloudFront. |
| short_desc | Full-stack React app with a serverless API. |
| repo | react-app |
| ref | how-to-create-a-reactjs-app-with-serverless |
| comments_id | how-to-create-a-react-js-app-with-serverless/2413 |
In this example we will look at how to use React.js with a [serverless]({% link _chapters/what-is-serverless.md %}) API to create a simple click counter app. We'll be using the [SST]({{ site.sst_github_repo }}) and the SST [ReactStaticSite]({{ site.docs_url }}/constructs/ReactStaticSite) construct to deploy our app to AWS.
- Node.js >= 10.15.1
- We'll be using TypeScript
- An [AWS account]({% link _chapters/create-an-aws-account.md %}) with the [AWS CLI configured locally]({% link _chapters/configure-the-aws-cli.md %})
{%change%} Let's start by creating an SST app.
$ npx create-sst@latest --template=minimal/typescript-starter react-app
$ cd react-app
$ npm installBy default, our app will be deployed to an environment (or stage) called dev and the us-east-1 AWS region. This can be changed in the sst.json in your project root.
{
"name": "react-app",
"region": "us-east-1",
"main": "stacks/index.ts"
}An SST app is made up of a couple of parts.
-
stacks/— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/directory of your project. SST uses [AWS CDK]({% link _chapters/what-is-aws-cdk.md %}), to create the infrastructure. -
services/— App CodeThe code that's run when your API is invoked is placed in the
services/directory of your project. -
frontend/— React AppThe code for our frontend React.js app.
Our app is made up of a simple API and a React.js app. The API will be talking to a database to store the number of clicks. We'll start by creating the database.
We'll be using Amazon DynamoDB; a reliable and highly-performant NoSQL database that can be configured as a true serverless database. Meaning that it'll scale up and down automatically. And you won't get charged if you are not using it.
{%change%} Replace the stacks/MyStack.ts with the following.
import {
Api,
ReactStaticSite,
StackContext,
Table,
} from "@serverless-stack/resources";
export function MyStack({ stack }: StackContext) {
// Create the table
const table = new Table(stack, "Counter", {
fields: {
counter: "string",
},
primaryIndex: { partitionKey: "counter" },
});
}This creates a serverless DynamoDB table using the SST [Table]({{ site.docs_url }}/constructs/Table) construct. It has a primary key called counter. Our table is going to look something like this:
| counter | tally |
|---|---|
| clicks | 123 |
Now let's add the API.
{%change%} Add this below the Table definition in stacks/MyStack.ts.
// Create the HTTP API
const api = new Api(stack, "Api", {
defaults: {
function: {
// Allow the API to access the table
permissions: [table],
// Pass in the table name to our API
environment: {
tableName: table.tableName,
},
},
},
routes: {
"POST /": "functions/lambda.handler",
},
});
// Show the URLs in the output
stack.addOutputs({
ApiEndpoint: api.url,
});We are using the SST [Api]({{ site.docs_url }}/constructs/Api) construct to create our API. It simply has one endpoint (the root). When we make a POST request to this endpoint the Lambda function called handler in services/functions/lambda.ts will get invoked.
We also pass in the name of our DynamoDB table to our API as an environment variable called tableName. And we allow our API to access (read and write) the table instance we just created.
To deploy a React.js app to AWS, we'll be using the SST [ReactStaticSite]({{ site.docs_url }}/constructs/ReactStaticSite) construct.
{%change%} Replace the following in stacks/MyStack.ts:
// Show the API endpoint in the output
stack.addOutputs({
ApiEndpoint: api.url,
});{%change%} With:
// Deploy our React app
const site = new ReactStaticSite(stack, "ReactSite", {
path: "frontend",
environment: {
REACT_APP_API_URL: api.url,
},
});
// Show the URLs in the output
stack.addOutputs({
SiteUrl: site.url,
ApiEndpoint: api.url,
});The construct is pointing to where our React.js app is located. We haven't created our app yet but for now we'll point to the frontend directory.
We are also setting up a build time React environment variable REACT_APP_API_URL with the endpoint of our API. The [ReactStaticSite]({{ site.docs_url }}/constructs/ReactStaticSite) allows us to set environment variables automatically from our backend, without having to hard code them in our frontend. You can read more about this over in our chapter on, [Setting serverless environments variables in a React app]({% link _chapters/setting-serverless-environments-variables-in-a-react-app.md %}).
You can also optionally configure a custom domain.
// Deploy our React app
const site = new ReactStaticSite(stack, "ReactSite", {
path: "frontend",
environment: {
REACT_APP_API_URL: api.url,
},
customDomain: "www.my-react-app.com",
});But we'll skip this for now.
Our API is powered by a Lambda function. In the function we'll read from our DynamoDB table.
{%change%} Replace services/functions/lambda.ts with the following.
import { DynamoDB } from "aws-sdk";
const dynamoDb = new DynamoDB.DocumentClient();
export async function handler() {
const getParams = {
// Get the table name from the environment variable
TableName: process.env.tableName,
// Get the row where the counter is called "clicks"
Key: {
counter: "clicks",
},
};
const results = await dynamoDb.get(getParams).promise();
// If there is a row, then get the value of the
// column called "tally"
let count = results.Item ? results.Item.tally : 0;
return {
statusCode: 200,
body: count,
};
}We make a get call to our DynamoDB table and get the value of a row where the counter column has the value clicks. Since we haven't written to this column yet, we are going to just return 0.
{%change%} Let's install the aws-sdk package in the services/ folder.
$ npm install aws-sdkAnd let's test what we have so far.
{%change%} SST features a [Live Lambda Development]({{ site.docs_url }}/live-lambda-development) environment that allows you to work on your serverless apps live.
$ npm startThe first time you run this command it'll take a couple of minutes to deploy your app and a debug stack to power the Live Lambda Development environment.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-react-app-my-stack: deploying...
✅ dev-react-app-my-stack
Stack dev-react-app-my-stack
Status: deployed
Outputs:
ApiEndpoint: https://51q98mf39e.execute-api.us-east-1.amazonaws.com
SiteUrl: https://d8lnp7p95pfac.cloudfront.net
The ApiEndpoint is the API we just created. While the SiteUrl is where our React app will be hosted. For now it's just a placeholder website.
Let's test our endpoint with the SST Console. The SST Console is a web based dashboard to manage your SST apps. [Learn more about it in our docs]({{ site.docs_url }}/console).
Go to the API tab and click Send button to send a POST request.
Note, The [API explorer]({{ site.docs_url }}/console#api) lets you make HTTP requests to any of the routes in your Api construct. Set the headers, query params, request body, and view the function logs with the response.
You should see a 0 in the response body.
We are now ready to use the API we just created. Let's use Create React App to setup our React.js app.
{%change%} Run the following in the project root.
$ npx create-react-app frontend --use-npm
$ cd frontendThis sets up our React app in the frontend/ directory. Recall that, earlier in the guide we were pointing the ReactStaticSite construct to this path.
Create React App will throw a warning if it is installed inside a repo that uses Jest. To disable this, we'll need to set an environment variable.
{%change%} Add the following to frontend/.env.
SKIP_PREFLIGHT_CHECK=trueWe also need to load the environment variables from our SST app. To do this, we'll be using the @serverless-stack/static-site-env package.
{%change%} Install the static-site-env package by running the following in the frontend/ directory.
$ npm install @serverless-stack/static-site-env --save-devWe need to update our start script to use this package.
{%change%} Replace the start script in your frontend/package.json.
"start": "react-scripts start",{%change%} With the following:
"start": "sst-env -- react-scripts start",Let's start our React development environment.
{%change%} In the frontend/ directory run.
$ npm run startThis should open up our React.js app in your browser.
We are now ready to add the UI for our app and connect it to our serverless API.
{%change%} Replace frontend/src/App.js with.
import { useState } from "react";
import "./App.css";
export default function App() {
const [count, setCount] = useState(null);
function onClick() {
fetch(process.env.REACT_APP_API_URL, {
method: "POST",
})
.then((response) => response.text())
.then(setCount);
}
return (
<div className="App">
{count && <p>You clicked me {count} times.</p>}
<button onClick={onClick}>Click Me!</button>
</div>
);
}Here we are adding a simple button that when clicked, makes a request to our API. We are getting the API endpoint from the environment variable, process.env.REACT_APP_API_URL.
The response from our API is then stored in our app's state. We use that to display the count of the number of times the button has been clicked.
Let's add some styles.
{%change%} Replace frontend/src/App.css with.
body,
html {
height: 100%;
display: grid;
}
#root {
margin: auto;
}
.App {
text-align: center;
}
p {
margin-top: 0;
font-size: 20px;
}
button {
font-size: 48px;
}Now if you head over to your browser, your React app should look something like this.
Of course if you click on the button multiple times, the count doesn't change. That's because we are not updating the count in our API. We'll do that next.
Let's update our table with the clicks.
{%change%} Add this above the return statement in services/functions/lambda.ts.
const putParams = {
TableName: process.env.tableName,
Key: {
counter: "clicks",
},
// Update the "tally" column
UpdateExpression: "SET tally = :count",
ExpressionAttributeValues: {
// Increase the count
":count": ++count,
},
};
await dynamoDb.update(putParams).promise();Here we are updating the clicks row's tally column with the increased count.
And if you head over to your browser and click the button again, you should see the count increase!
Also let's go to the DynamoDB tab in the SST Console and check that the value has been updated in the table.
Note, The [DynamoDB explorer]({{ site.docs_url }}/console#dynamodb) allows you to query the DynamoDB tables in the [Table]({{ site.docs_url }}/constructs/Table) constructs in your app. You can scan the table, query specific keys, create and edit items.
{%change%} To wrap things up we'll deploy our app to prod.
$ npx sst deploy --stage prodThis allows us to separate our environments, so when we are working in dev, it doesn't break the app for our users.
Once deployed, you should see something like this.
✅ prod-react-app-my-stack
Stack prod-react-app-my-stack
Status: deployed
Outputs:
ApiEndpoint: https://ck198mfop1.execute-api.us-east-1.amazonaws.com
SiteUrl: https://d1wuzrecqjflrh.cloudfront.netRun the below command to open the SST Console in prod stage to test the production endpoint.
npx sst console --stage prodGo to the API tab and click Send button to send a POST request.
If you head over to the SiteUrl in your browser, you should see your new React app in action!
Finally, you can remove the resources created in this example using the following commands.
$ npx sst remove
$ npx sst remove --stage prodAnd that's it! We've got a completely serverless click counter in React.js. A local development environment, to test and make changes. And it's deployed to production as well, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!





