Mastering AWS Amplify CLI: A Comprehensive Guide with Hands-On Examples

AWS Amplify is a powerful set of tools and services designed to help developers build full-stack applications quickly. The Amplify CLI is the backbone of this framework, enabling developers to configure and manage cloud resources efficiently.
In this guide, we’ll deep dive into each Amplify CLI command, understanding how they work with hands-on examples.
1. Introduction to Amplify CLI
Amplify CLI is a command-line tool that interacts with AWS services, helping developers initialize, configure, and manage Amplify projects. It is essential for setting up authentication, APIs, hosting, and other backend functionalities.
2. Installing & Setting Up Amplify CLI
Before using Amplify CLI, install it globally using npm:
npm install -g @aws-amplify/cli
After installation, configure AWS credentials:
amplify configure
This command sets up Amplify with your AWS account.
3. Core Commands Overview
Below are the most frequently used Amplify CLI commands:
Command | Purpose |
amplify init | Initialize an Amplify project |
amplify add auth | Add authentication (Cognito) to your project |
amplify add api | Add GraphQL or REST API backend |
amplify push | Deploy changes to AWS |
amplify status | View the current status of Amplify resources |
amplify hosting configure | Set up hosting options for the project |
4. Detailed Explanation of Each Command
a. amplify init
– Initialize a Project
This command sets up your Amplify project within your directory.
amplify init
It prompts you for a project name and environment (dev/staging/prod).
Allows you to choose a backend provider.
b. amplify add auth
– Authentication Setup
To add authentication using AWS Cognito:
amplify add auth
You will get options like user sign-in, multi-factor authentication (MFA), and more.
c. amplify add api
– API Integration
Add an API to your project:
amplify add api
Choose between GraphQL and REST APIs.
Configure permissions for accessing the API.
d. amplify push
– Deploy Changes
Once you’ve made changes to your project, deploy them to AWS using:
amplify push
It uploads and provisions cloud resources.
5. Examples & Hands-On Walkthrough
Example 1: Building an Authentication System
Initialize a project:
amplify init
Add authentication:
amplify add auth
Deploy your authentication setup:
amplify push
Integrate Amplify’s authentication module into your React project:
import { Auth } from 'aws-amplify';
const signIn = async () => {
try {
const user = await Auth.signIn('username', 'password');
console.log('Logged in:', user);
} catch (error) {
console.error('Error signing in', error);
}
};
Example 2: Setting Up a GraphQL API
Initialize a project:
amplify init
Add a GraphQL API:
amplify add api
Define your schema inside
schema.graphql
:
type Todo @model {
id: ID!
name: String!
description: String
}
Push the API:
amplify push
Use AWS AppSync to make GraphQL queries.
6. Common Troubleshooting & Best Practices
Use
amplify status
to check the state of your backend resources before pushing updates.Always test configurations locally before deploying.
Use
amplify remove <feature>
if you need to delete services like authentication or API from the project.
Here’s a more extensive list of AWS Amplify CLI commands for easy reference:
Command | Purpose |
amplify init | Initialize a new Amplify project |
amplify configure | Configure Amplify with AWS credentials |
amplify add auth | Add authentication using Amazon Cognito |
amplify add api | Add a GraphQL or REST API backend |
amplify add storage | Add storage (S3 bucket) to your project |
amplify add function | Add a Lambda function |
amplify add analytics | Add analytics tracking via AWS Pinpoint |
amplify add notifications | Add notifications using AWS SNS |
amplify add predictions | Add AI/ML predictions using AWS services |
amplify add hosting | Add hosting for web applications |
amplify add geo | Add location-based services using Amazon Location Service |
amplify push | Deploy changes to AWS |
amplify status | Show the current status of resources |
amplify remove <feature> | Remove a previously added feature (e.g., auth, API) |
amplify hosting configure | Configure hosting for web deployment |
amplify delete | Remove an Amplify project permanently |
Of course! Here are hands-on examples for each Amplify CLI command listed earlier. 🚀
1. amplify init
– Initialize an Amplify Project
This command initializes a new Amplify project in your directory.
amplify init
Steps:
Enter project name.
Choose your framework (React, Angular, Vue, etc.).
Select a backend environment (dev/staging/prod).
Connect to AWS account.
2. amplify configure
– Configure AWS Credentials
Set up AWS credentials for Amplify.
amplify configure
Steps:
Opens AWS Console to create access keys.
Set up a default AWS profile.
3. amplify add auth
– Add Authentication
Adds authentication using AWS Cognito.
amplify add auth
Example:
Enable email and password authentication:
? Do you want to use default authentication settings? Yes
? Allow unauthenticated users? No
? Multi-factor authentication? Optional
After pushing changes (amplify push
), integrate authentication in React:
import { Auth } from 'aws-amplify';
async function signUp(username, password, email) {
try {
await Auth.signUp({
username,
password,
attributes: { email },
});
console.log('User signed up successfully!');
} catch (error) {
console.error('Sign-up error:', error);
}
}
4. amplify add api
– Create an API
Adds a GraphQL or REST API to your project.
amplify add api
Example:
Set up a GraphQL API:
type Todo @model {
id: ID!
name: String!
description: String
}
Query example using Amplify API module:
import { API, graphqlOperation } from 'aws-amplify';
import { listTodos } from './graphql/queries';
async function fetchTodos() {
try {
const todoData = await API.graphql(graphqlOperation(listTodos));
console.log(todoData);
} catch (error) {
console.error('Error fetching todos:', error);
}
}
5. amplify add storage
– Add an S3 Storage Bucket
Enables file storage using AWS S3.
amplify add storage
Example:
Upload a file in React:
import { Storage } from 'aws-amplify';
async function uploadFile(file) {
try {
await Storage.put(file.name, file, { contentType: file.type });
console.log('File uploaded successfully!');
} catch (error) {
console.error('Upload error:', error);
}
}
6. amplify add function
– Add a Lambda Function
Creates a Lambda function for backend processing.
amplify add function
Example:
Define your function in index.js
:
exports.handler = async (event) => {
console.log('Event received:', event);
return { statusCode: 200, body: JSON.stringify('Hello from Lambda!') };
};
7. amplify add notifications
– Enable AWS SNS Notifications
Adds push notifications or SMS alerts.
amplify add notifications
Example:
Send an SMS notification using SNS:
import { Notifications } from 'aws-amplify';
async function sendSMS() {
try {
await Notifications.SMS.send({
phoneNumber: '+911234567890',
message: 'Welcome to AWS Amplify!',
});
} catch (error) {
console.error('SMS Error:', error);
}
}
8. amplify push
– Deploy Changes to AWS
Push all local changes to the AWS cloud.
amplify push
This provisions backend resources based on the project configuration.
9. amplify status
– Check Resource Status
Displays the current state of Amplify resources.
amplify status
Example output:
| Category | Resource | Status | Provider |
|-----------|---------|---------|----------|
| Auth | Cognito | Created | AWS |
| API | GraphQL | Updated | AWS |
| Storage | S3 | Created | AWS |
10. amplify hosting configure
– Set Up Hosting
Configures Amplify Hosting for your project.
amplify hosting configure
Steps:
Choose static or dynamic hosting (S3, CloudFront).
Set deployment method (manual or CI/CD).
11. amplify delete
– Remove an Amplify Project
Deletes an entire Amplify project and associated AWS resources.
amplify delete
⚠️ Warning: Use this with caution, as it cannot be undone.
In industry settings, developers working with AWS Amplify often rely on certain commands for CI/CD pipelines, multi-environment management, and advanced debugging.
Here are some frequently used commands in enterprise-grade projects:
1. amplify env list
– List All Environments
This command is used to check available environments in your Amplify project.
amplify env list
Example output:
| Env Name | Provider | Status |
|----------|---------|---------|
| dev | AWS | Active |
| staging | AWS | Idle |
| prod | AWS | Active |
2. amplify env checkout <env>
– Switch Environments
Used to switch between different environments (dev, staging, prod).
amplify env checkout staging
Developers use this when working on multiple teams with separate environments.
3. amplify override auth
– Customize Authentication
This allows custom overrides for Cognito authentication settings.
amplify override auth
For example, modify Cognito attributes in override.ts
:
import * as cognito from '@aws-cdk/aws-cognito';
export function override(resources) {
resources.userPool.passwordPolicy = {
minLength: 10,
requireNumbers: true,
requireUppercase: true,
};
}
4. amplify api gql-compile
– Compile GraphQL API
Used to verify and compile GraphQL schemas locally before deploying.
amplify api gql-compile
Helps developers catch schema errors before deploying.
5. amplify mock api
– Local API Mocking
Allows local testing for GraphQL or REST APIs before deployment.
amplify mock api
Developers use this command to test API endpoints without interacting with AWS AppSync.
6. amplify api migrate
– Migrate API Versions
Used when upgrading GraphQL APIs with schema changes.
amplify api migrate
Example output:
✔ GraphQL schema changes detected.
✔ Migrating to version v2...
✔ Update successful!
7. amplify hosting publish
– Publish Static Website
Directly deploy frontend assets (React, Angular, Vue) with one command.
amplify hosting publish
Example output:
✔ Website deployed at https://myapp.amplifyapp.com
Popular in production-ready deployments.
8. amplify function build
– Build Lambda Functions
Used to compile & test AWS Lambda functions locally.
amplify function build
9. amplify console
– Open Amplify Console
Opens the AWS Amplify admin dashboard.
amplify console
10. amplify delete
– Cleanup Project
Completely removes all Amplify resources from AWS.
amplify delete
⚠️ Warning: Used rarely, but necessary when shutting down projects.
Subscribe to my newsletter
Read articles from Piyush Kabra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
