Building your first Fullstack Serverless App with Angular and AWS Amplify
In this workshop we'll learn how to build cloud-enabled web applications with Angular & AWS Amplify.
Topics we'll be covering:
- Authentication
- GraphQL API with AWS AppSync
- Mocking and Testing
- Predictions
- Hosting
- Multiple Environments
- Deploying via the Amplify Console
- Run locally via Amplify CLI
- Removing / Deleting Services
Pre-requisites
- Node:
14.7.0
. Visit Node - npm:
6.14.7
. Packaged with Node otherwise run upgrade
npm install -g npm
Getting Started - Creating the Application
To get started, we first need to create a new Angular project & change into the new directory using the Angular CLI.
If you already have it installed, skip to the next step. If not, either install the CLI & create the app or create a new app using:
npm install -g @angular/cli
ng new amplify-app
Now change into the new app directory and make sure it runs
cd amplify-app
npm install
ng serve
Changes to Angular CLI project
Add type definitions for Node by changing src/tsconfig.app.json
. This is a requirement from aws-js-sdk
.
{
"compilerOptions": {
"types": ["node"]
},
}
Add the following code, to the top of src/polyfills.ts
. This is a requirement for Angular 6+.
(window as any).global = window;
(window as any).process = {
env: { DEBUG: undefined },
};
Installing the CLI & Initializing a new AWS Amplify Project
Let's now install the AWS Amplify & AWS Amplify Angular libraries:
npm install --save @aws-amplify/auth @aws-amplify/api @aws-amplify/pubsub @aws-amplify/storage @aws-amplify/ui-angular
Installing the AWS Amplify CLI
Next, we'll install the AWS Amplify CLI:
npm install -g @aws-amplify/cli
Now we need to configure the CLI with our credentials:
amplify configure
If you'd like to see a video walkthrough of this configuration process, click here.
Here we'll walk through the amplify configure
setup. Once you've signed in to the AWS console, continue:
- Specify the AWS Region: eu-central-1(Frankfurt)
Find out the best AWS Region to host your app (lower latency is best): AWS latency test, CloudPing.info.
- Specify the username of the new IAM user: amplify-app
In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, & Create User to create the new IAM user. Then, return to the command line & press Enter.
- Enter the access key of the newly created user:
accessKeyId: (<YOUR_ACCESS_KEY_ID>)
secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>) - Profile Name: default
To view the new created IAM User go to the dashboard at https://console.aws.amazon.com/iam/home#/users/. Also be sure that your region matches your selection.
Initializing A New Project
amplify init
- Enter a name for the project: amplify-app
- Enter a name for the environment: dev
- Choose your default editor: Visual Studio Code
- Please choose the type of app that you're building javascript
- What javascript framework are you using angular
- Source Directory Path: src
- Distribution Directory Path: dist/amplify-app
- Build Command: npm run-script build
- Start Command: ng serve
- Please choose the profile you want to use: default
- Do you want to use an AWS profile? Yes
- Please choose the profile you want to use default
Now, the AWS Amplify CLI has iniatilized a new project & you will see a new folder: amplify. The files in this folder hold your project configuration.
<amplify-app>
|_ amplify
|_ .config
|_ #current-cloud-backend
|_ backend
team-provider-info.json
Adding Authentication
To add authentication, we can use the following command:
amplify add auth
When prompted choose
- Do you want to use default authentication and security configuration?: Default configuration
- How do you want users to be able to sign in when using your Cognito User Pool?: Username
- What attributes are required for signing up? (Press to select, to toggle all, to invert selection): Email
Now, we'll run the push command and the cloud resources will be created in our AWS account.
amplify push
Current Environment: dev
| Category | Resource name | Operation | Provider plugin |
| -------- | ------------------ | --------- | ----------------- |
| Auth | amplifyappuuid | Create | awscloudformation |
? Are you sure you want to continue? Yes
To quickly check your newly created Cognito User Pool you can run
amplify status
To access the AWS Cognito Console at any time, go to the dashboard at https://console.aws.amazon.com/cognito/. Also be sure that your region is set correctly.
Configuring the Angular Application
Now, our resources are created & we can start using them!
The first thing we need to do is to configure our Angular application to be aware of our new AWS Amplify project. We can do this by referencing the auto-generated aws-exports.js
file that is now in our src
folder.
To configure the app, open main.ts and add the following code below the last import:
import Auth from '@aws-amplify/auth';
import API from '@aws-amplify/api';
import PubSub from '@aws-amplify/pubsub';
import amplify from './aws-exports';
Auth.configure(amplify);
API.configure(amplify);
PubSub.configure(amplify);
Now, our app is ready to start using our AWS services.
Importing the Angular Module
Add the Amplify UI Module to src/app/app.module.ts
:
import { AmplifyUIAngularModule } from '@aws-amplify/ui-angular';
@NgModule({
imports: [
AmplifyUIAngularModule
],
});
Using the Authenticator Component
AWS Amplify provides UI components that you can use in your App. Let's add these components to the project
In order to use the Authenticator Component add it to src/app/app.component.html:
<amplify-authenticator></amplify-authenticator>
Now, we can run the app and see that an Authentication flow has been added in front of our App component. This flow gives users the ability to sign up & sign in.
To view any users that were created, go back to the Cognito dashboard at https://console.aws.amazon.com/cognito/. Also be sure that your region is set correctly.
Alternatively we can also use
amplify console auth
Accessing User Data
We can access the user's info now that they are signed in by calling currentAuthenticatedUser()
which returns a Promise.
import Auth from '@aws-amplify/auth';
@Component(...)
export class AppComponent {
constructor() {
Auth.currentAuthenticatedUser().then(console.log)
}
}
Managing authentication states
The Authenticator
Component goes through different states as the user interacts with the authentication flow. Let's see a more advanced example of showing a welcome message to the user once is logged in:
Replace the content of src/app/app.component.html with:
<div>
<amplify-authenticator *ngIf="!signedIn"></amplify-authenticator>
<div *ngIf="signedIn && user">
<div>Hello, {{user.username}}</div>
<amplify-sign-out></amplify-sign-out>
</div>
</div>
In our component make the following changes
import { Component, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';
import { onAuthUIStateChange, CognitoUserInterface, AuthState } from '@aws-amplify/ui-components';
import Auth from '@aws-amplify/auth';
@Component(...)
export class AppComponent implements OnInit, OnDestroy {
user: CognitoUserInterface | undefined;
signedIn: boolean;
constructor(private ref: ChangeDetectorRef) {
Auth.currentAuthenticatedUser().then(console.log)
}
ngOnInit() {
onAuthUIStateChange((authState, authData) => {
this.signedIn = authState === AuthState.SignedIn;
this.user = authData as CognitoUserInterface;
this.ref.detectChanges();
})
}
ngOnDestroy() {
return onAuthUIStateChange;
}
}
Custom authentication strategies
The Authenticator
Component is a really easy way to get up and running with authentication, but in a real-world application we probably want more control over how our form looks & functions.
Let's look at how we might create our own authentication flow.
To get started, we would probably want to create input fields that would hold user input data in the state. For instance when signing up a new user, we would probably need 2 inputs to capture the user's email & password.
To do this, we could create a form like:
<form [formGroup]="signup" (ngSubmit)="onSignup(signup.value)">
<div>
<label>Email: </label>
<input type="email" formControlName="email">
</div>
<div>
<label>Password: </label>
<input type="password" formControlName="password">
</div>
<button type="submit">Submit</button>
</form>
We'd also need to have a method that signed up & signed in users. We can us the Auth class to do this. The Auth class has over 30 methods including things like signUp
, signIn
, confirmSignUp
, confirmSignIn
, & forgotPassword
. These functions return a promise so they need to be handled asynchronously.
import Auth from '@aws-amplify/auth';
export class SignupComponent implements OnInit {
public signup: FormGroup;
constructor(
private fb: FormBuilder,
) { }
ngOnInit() {
this.signup = this.fb.group({
'email': ['', Validators.required],
'password': ['', Validators.required]
});
}
onSignup(value: any) {
const email = value.email, password = value.password;
Auth.signUp(email, password).then( _ => {
this.success = true;
}).catch(console.log);
}
Adding a GraphQL API
To add a GraphQL API, we can use the following command:
amplify add api
Answer the following questions
- Please select from one of the below mentioned services GraphQL
- Provide API name: RestaurantAPI
- Choose the default authorization type for the API API key
- Enter a description for the API key: (empty)
- After how many days from now the API key should expire (1-365): 7
- Do you want to configure advanced settings for the GraphQL API No, I am done.
- Do you have an annotated GraphQL schema? No
- Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)
- Do you want to edit the schema now? Yes
When prompted, update the schema to the following:
type Restaurant @model {
id: ID!
name: String!
description: String!
city: String!
}
Note: Don't forget to save the changes to the schema file!
Next, let's push the configuration to our account:
amplify push
- Are you sure you want to continue? Yes
- Do you want to generate code for your newly created GraphQL API Yes
- Choose the code generation language target angular
- Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.graphql
- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
- Enter maximum statement depth [increase from default if your schema is deeply nested] 2
- Enter the file name for the generated code src/app/API.service.ts
Notice your GraphQL endpoint and API KEY.
This step created a new AWS AppSync API. Use the command below to access the AWS AppSync dashboard. Make sure that your region is correct.
amplify console api
- Please select from one of the below mentioned services GraphQL
Local mocking and testing
To mock and test the API locally, you can run the mock
command:
amplify mock api
Note: local mocking requires Java SDK
- Choose the code generation language target: javascript
- Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js
- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Y
- Enter maximum statement depth [increase from default if your schema is deeply nested]: 2
This should open up the local GraphiQL editor.
From here, we can now test the API locally.
Adding mutations from within the AWS AppSync Console
In the AWS AppSync console, on the left side click on Queries.
Execute the following mutation to create a new restaurant in the API:
mutation createRestaurant {
createRestaurant(input: {
name: "Nobu"
description: "Great Sushi"
city: "New York"
}) {
id name description city
}
}
Now, let's query for the restaurant:
query listRestaurants {
listRestaurants {
items {
id
name
description
city
}
}
}
We can even add search / filter capabilities when querying:
query searchRestaurants {
listRestaurants(filter: {
city: {
contains: "New York"
}
}) {
items {
id
name
description
city
}
}
}
Interacting with the GraphQL API from our client application - Querying for data
Now that the GraphQL API is created we can begin interacting with it!
The first thing we'll do is perform a query to fetch data from our API.
To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.
Read more about the Amplify GraphQL Client here.
import { APIService } from '../API.service';
import { Restaurant } from './../types/restaurant';
@Component({
template: `
<div>
<div *ngFor="let restaurant of restaurants">
{{ restaurant.name }}
</div>
</div>`
})
export class AppComponent implements OnInit {
restaurants: Array<Restaurant>;
constructor(private api: APIService) { }
ngOnInit() {
this.api.ListRestaurants().then(event => {
this.restaurants = event.items;
});
}
}
Performing mutations
Now, let's look at how we can create mutations.
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component(...)
export class HomeComponent implements OnInit {
public createForm: FormGroup;
constructor(private api: APIService, private fb: FormBuilder) { }
async ngOnInit() {
this.createForm = this.fb.group({
'name': ['', Validators.required],
'description': ['', Validators.required],
'city': ['', Validators.required]
});
this.api.ListRestaurants().then(event => {
this.restaurants = event.items;
});
}
public onCreate(restaurant: any) {
this.api.CreateRestaurant(restaurant).then(event => {
console.log('item created!');
this.createForm.reset();
})
.catch(e => {
console.log('error creating restaurant...', e);
});
}
}
GraphQL Subscriptions
Next, let's see how we can create a subscription to subscribe to changes of data in our API.
To do so, we need to define the subscription, listen for the subscription, & update the state whenever a new piece of data comes in through the subscription.
@Component(...)
export class HomeComponent implements OnInit {
ngOnInit() {
//Subscribe to changes
this.api.OnCreateRestaurantListener.subscribe( (event: any) => {
const newRestaurant = event.value.data.onCreateRestaurant;
this.restaurants = [newRestaurant, ...this.restaurants];
});
Adding Predictions
To add the predictions category to our Amplify project, we can use the following command:
amplify add predictions
Identify Text, Labels and Entities
- Please select from one of the categories below Identify
- What would you like to identify? Identify Text
- Provide a friendly name for your resource identifyTextId
- Would you also like to identify documents? No
- Who should have access? Auth and Guest users
Translate Text
- Please select from one of the categories below Convert
- What would you like to convert? Translate text into a different language
- Provide a friendly name for your resource translateTextId
- What is the source language? English
- What is the target language? Spanish
- Who should have access? Auth and Guest users
Generate Speech
- Please select from one of the categories below Convert
- What would you like to convert? Generate speech audio from text
- Provide a friendly name for your resource speechGeneratorId
- What is the source language? British English
- Select a speaker Brian - Male
- Who should have access? Auth and Guest users
Transcribe Audio
- Please select from one of the categories below Convert
- What would you like to convert? Transcribe text from audio
- Provide a friendly name for your resource transcriptiondId
- What is the source language? British English
- Who should have access? Auth and Guest users
Interpret Text
- Please select from one of the categories below Interpret
- What would you like to interpret? Interpret Text
- Provide a friendly name for your resource interpretTextId
- What kind of interpretation would you like? All
- Who should have access? Auth and Guest users
Now, we'll run the push command and the cloud resources will be created in our AWS account.
amplify push
Configuring the Vue Application
Now, our resources are created & we can start using them!
To configure the app, open main.js and add the following code below the last import:
import Predictions, { AmazonAIPredictionsProvider } from '@aws-amplify/predictions';
Predictions.addPluggable(new AmazonAIPredictionsProvider());
Now, our app is ready to start using Predictions.
Translate Example
The result of Predictions.convert(config)
will be a promise. If successful will return the translation otherwise will return the input as-is.
Predictions.convert({
translateText: {
source: {
text: "My taylor is rich!",
language: "en"
},
targetLanguage: "es"
}
})
.then(({text}) => {
this.translation = text;
})
List of supported languages to translate from.
Detect Language Example
The result of Predictions.interpret(config)
call will return a promise. If successful, we will be able to pick the main language as part of the results as demonstrated in the following code snipet.
Predictions.interpret({
text: {
source: {
text: textToInterpret,
},
type: InterpretTextCategories.LANGUAGE
}
})
.then((result) => {
let detected = result.textInterpretation.language;
})
Text to Speech Example
The result of Predictions.convert(config)
call will return a promise with the resulting audio file which we can reference to play the voice using HMTL Audio.
Predictions.convert({
textToSpeech: {
source: {
text: textToTranslate,
},
voiceId: "Brian"
}
})
.then((result) => {
if (result.speech.url) {
this.audio = new Audio();
this.audio.src = result.speech.url;
this.audio.play();
}
})
Hosting
To deploy & host your app on AWS, we can use the hosting
category.
amplify add hosting
- Select the environment setup: DEV (S3 only with HTTP)
- hosting bucket name YOURBUCKETNAME
- index doc for the website index.html
- error doc for the website index.html
Now, everything is set up & we can publish it:
amplify publish
Working with multiple environments
You can create multiple environments for your application in which to create & test out new features without affecting the main environment which you are working on.
When you create a new environment from an existing environment, you are given a copy of the entire backend application stack from the original project. When you make changes in the new environment, you are then able to test these new changes in the new environment & merge only the changes that have been made since the new environment was created back into the original environment.
Let's take a look at how to create a new environment. In this new environment, we'll re-configure the GraphQL Schema to have another field for the pet owner.
First, we'll initialize a new environment using amplify init
:
amplify init
- Do you want to use an existing environment? N
- Enter a name for the environment: apiupdate
- Do you want to use an AWS profile? Y
- amplify-workshop-user
Once the new environment is initialized, we should be able to see some information about our environment setup by running:
amplify env list
| Environments |
| ------------ |
| dev |
| *apiupdate |
Now we can update the GraphQL Schema in amplify/backend/api/RestaurantAPI/schema.graphql
to the following (adding the owner field):
type Restaurant @model {
...
owner: String
}
Now, we can create this new stack by running amplify push
:
amplify push
After we test it out, we can now merge it into our original dev environment:
amplify env checkout dev
amplify status
amplify push
- Do you want to update code for your updated GraphQL API? Y
- Do you want to generate GraphQL statements? Y
Deploying via the Amplify Console
We have looked at deploying via the Amplify CLI hosting category, but what about if we wanted continous deployment? For this, we can use the Amplify Console to deploy the application.
The first thing we need to do is create a new GitHub repo for this project. Once we've created the repo, we'll copy the URL for the project to the clipboard & initialize git in our local project:
git init
git remote add origin git@github.com:username/project-name.git
git add .
git commit -m 'initial commit'
git push origin master
Next we'll visit the Amplify Console in our AWS account:
amplify console
Here, we'll click Get Started to create a new deployment. Next, authorize Github as the repository service.
Next, we'll choose the new repository & branch for the project we just created & click Next.
In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click Next.
Finally, we can click Save and Deploy to deploy our application!
Now, we can push updates to Master to update our application.
Run locally with the Amplify CLI
- Install and configure the Amplify CLI
npm install -g @aws-amplify/cli
amplify configure
- Install and configure the Amplify CLI
amplify init --app https://github.com/gsans/fullstack-serverless-amplify-angular
The init command clones the GitHub repo, initializes the CLI, creates a ‘sampledev’ environment in CLI, detects and adds categories, provisions the backend, pushes the changes to the cloud, and starts the app.
- Provisioning the frontend and backend
Once the process is complete, the CLI will automatically open the app in your default browser.
Removing Services
If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the amplify remove
command:
amplify remove auth
amplify push
If you are unsure of what services you have enabled at any time, you can run the amplify status
command:
amplify status
amplify status
will give you the list of resources that are currently enabled in your app.
Deleting entire project
amplify delete
Appendix
Setup your AWS Account
In order to follow this workshop you need to create and activate an Amazon Web Services account.
Follow the steps here
Trobleshooting
Message: The AWS Access Key Id needs a subscription for the service
Solution: Make sure you are subscribed to the free plan. Subscribe
Message: TypeError: fsevents is not a constructor
Solution: npm audit fix --force