Options
All
  • Public
  • Public/Protected
  • All
Menu

AWS Amplify

Gitter Chat
npm downloads build:started

AWS Amplify is a JavaScript library for frontend and mobile developers building cloud-enabled applications.

AWS Amplify provides a declarative and easy-to-use interface across different categories of cloud operations. AWS Amplify goes well with any JavaScript based frontend workflow, and React Native for mobile developers.

Our default implementation works with Amazon Web Services (AWS), but AWS Amplify is designed to be open and pluggable for any custom backend or service.

Notice:

Amplify@1.x.x has structural changes. For details please check Amplify Modularization.

Features / APIs

  • Authentication: APIs and building blocks for developers who want to create user authentication experiences.
  • Analytics: Easily collect analytics data for you app. Analytics data includes user sessions and other custom events that you want to track in your app.
  • API: Provides a simple solution when making HTTP requests. It provides an automatic, lightweight signing process which complies with AWS Signature Version 4.
  • GraphQL Client: Interact with your GraphQL server or AWS AppSync API with an easy to use & configure GraphQL client.
  • Storage: Provides a simple mechanism for managing user content for your app in public, protected or private storage buckets.
  • Push Notifications: Allows you to integrate push notifications in your app with Amazon Pinpoint targeting and campaign management support.
  • Interactions: Create conversational bots powered by deep learning technologies..
  • PubSub: Provides connectivity with cloud-based message-oriented middleware.
  • Internationalization: A lightweight internationalization solution.
  • Cache: Provides a generic LRU cache for JavaScript developers to store data with priority and expiration settings.

Visit our Web Site to learn more about AWS Amplify.

Installation

AWS Amplify is available as aws-amplify package on npm

Web

$ npm install aws-amplify --save

or you could install the module you want to use individually:

$ npm install @aws-amplify/auth --save

React

If you are developing a React app, you can install an additional package aws-amplify-react containing Higher Order Components:

$ npm install aws-amplify --save
$ npm install aws-amplify-react --save

Angular

If you are developing an Angular app, you can install an additional package aws-amplify-angular. This package contains an Angular module with a provider and components:

$ npm install aws-amplify --save
$ npm install aws-amplify-angular --save

Visit our Installation Guide for Web to start building your web app.

Vue

If you are developing a Vue app, you can install an additional package aws-amplify-vue. This package contains a Vue plugin for the Amplify library along with Vue components.

$ npm install aws-amplify --save
$ npm install aws-amplify-vue --save

Visit our Installation Guide for Web to start building your Vue app.

React Native

For React Native development, install aws-amplify

$ npm install aws-amplify --save

If you are developing a React Native app, you can install an additional package aws-amplify-react-native containing Higher Order Components:

$ npm install aws-amplify-react-native --save

Visit our Installation Guide for React Native to start building your web app.

Configuration

Somewhere in your app, preferably at the root level, configure Amplify with your resources.

Using AWS Resources

import Amplify from 'aws-amplify';
import aws_exports from './aws-exports';

Amplify.configure(aws_exports);

// or you don't want to install all the categories
import Amplify from '@aws-amplify/core';
import Auth from '@aws-amplify/auth';
import aws_exports from './aws-exports';

// in this way you are only importing Auth and configuring it.
Amplify.configure(aws_exports);

Without AWS

Amplify.configure({
  API: {
    graphql_endpoint: 'https://www.example.com/my-graphql-endpoint'
  }
});

Examples

AWS Amplify supports many category scenarios such as Auth, Analytics, APIs and Storage as outlined in the Developer Guide. A couple of samples are below:

1. Collect user session metrics

By default, AWS Amplify can collect user session tracking data with a few lines of code:

import Analytics from '@aws-amplify/analytics';

Analytics.record('myCustomEvent');

See our Analytics Developer Guide for detailed information.

2. Add Authentication to your App

Add user sign up and sign in using two of the many methods available to the Auth class:

import Auth from '@aws-amplify/auth';

Auth.signUp({
  username: 'AmandaB',
  password: 'MyCoolPassword1!',
  attributes: {
    email: 'someemail@example.com'
  }
});

Auth.signIn(username, password)
  .then(success => console.log('successful sign in'))
  .catch(err => console.log(err));

See our Authentication Developer Guide for detailed information.

React / React Native

Adding authentication to your React or React Native app is as easy as wrapping your app's main component with our withAuthenticator higher order component. AWS Amplify will provide you customizable UI for common use cases such as user registration and login.


// For React
import { withAuthenticator } from 'aws-amplify-react';

// For React Native
import { withAuthenticator } from 'aws-amplify-react-native';

export default withAuthenticator(App);

Angular

To add authentication to your Angular app you can also use the built-in service provider and components:

// app.component.ts
import { AmplifyService }  from 'aws-amplify-angular';

...

constructor( public amplify:AmplifyService ) {
  // handle auth state changes
  this.amplify.authStateChange$
    .subscribe(authState => {
      this.authenticated = authState.state === 'signedIn';
      if (!authState.user) {
        this.user = null;
      } else {
        this.user = authState.user;
      }
  });
}

// app.component.html
<amplify-authenticator></amplify-authenticator>

See our Angular Guide for more details on Angular setup and usage.

3. Sign HTTP requests

AWS Amplify automatically signs your REST requests with AWS Signature Version 4 when using the API module :

import API from '@aws-amplify/api';

let apiName = 'MyApiName';
let path = '/path'; 
let options = {
  headers: {...} // OPTIONAL
}
API.get(apiName, path, options).then(response => {
  // Add your code here
});

See our API Developer Guide for detailed information.

4. GraphQL API Operations

To access a GraphQL API with your app, you need to make sure to configure the endpoint URL in your app’s configuration.

// configure a custom GraphQL endpoint
Amplify.configure({
  API: {
    graphql_endpoint: 'https://www.example.com/my-graphql-endpoint'
  }
});


// Or configure an AWS AppSync endpoint.
let myAppConfig = {
  // ...
  'aws_appsync_graphqlEndpoint': 'https://xxxxxx.appsync-api.us-east-1.amazonaws.com/graphql',
  'aws_appsync_region': 'us-east-1',
  'aws_appsync_authenticationType': 'API_KEY',
  'aws_appsync_apiKey': 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx',
  // ...
};

Amplify.configure(myAppConfig);

queries

import API, { graphqlOperation } from "@aws-amplify/api";

const ListEvents = `query ListEvents {
  listEvents {
    items {
      id
      where
      description
    }
  }
}`;

const allEvents = await API.graphql(graphqlOperation(ListEvents));

mutations

import API, { graphqlOperation } from "@aws-amplify/api";

const CreateEvent = `mutation CreateEvent($name: String!, $when: String!, $where: String!, $description: String!) {
  createEvent(name: $name, when: $when, where: $where, description: $description) {
    id
    name
    where
    when
    description
  }
}`;

const eventDetails = {
  name: 'Party tonight!',
  when: '8:00pm',
  where: 'Ballroom',
  decription: 'Coming together as a team!'
};

const newEvent = await API.graphql(graphqlOperation(CreateEvent, eventDetails));

subscriptions

import API, { graphqlOperation } from "@aws-amplify/api";

const SubscribeToEventComments = `subscription subscribeToComments {
  subscribeToComments {
    commentId
    content
  }
}`;

const subscription = API.graphql(
  graphqlOperation(SubscribeToEventComments)
).subscribe({
  next: (eventData) => console.log(eventData)
});

See our GraphQL API Developer Guide for detailed information.

5. Upload and Download public or private content

AWS Amplify provides an easy-to-use API to store and get content from public or private storage folders:

Storage.put(key, fileObj, {level: 'private'})
  .then (result => console.log(result))
  .catch(err => console.log(err));

  // Stores data with specifying its MIME type
Storage.put(key, fileObj, {
  level: 'private',
  contentType: 'text/plain'
})
.then (result => console.log(result))
.catch(err => console.log(err));

See our Storage Developer Guide for detailed information.

Index

Classes

Interfaces

Type aliases

Variables

Functions

Object literals

Type aliases

SumerianSceneOptions

SumerianSceneOptions: SceneOptions & object

Variables

Const API

API: APIClass = _instance

Const Analytics

Analytics: AnalyticsClass = _instance

Const AsyncStorage

AsyncStorage: Storage = JS.browserOrNode().isBrowser ? window.localStorage : undefined

Const Auth

Auth: AuthClass = _instance

Const BUFFER_SIZE

BUFFER_SIZE: 1000 = 1000

Const DEFAULT_ALGORITHM

DEFAULT_ALGORITHM: "AWS4-HMAC-SHA256" = "AWS4-HMAC-SHA256"

Const DEFAULT_PORT

DEFAULT_PORT: RegExp = RegExp(':(' + HTTP_PORT + '|' + HTTPS_PORT + ')$')

Const DEFAULT_PROVIDER_NAME

DEFAULT_PROVIDER_NAME: "SumerianProvider" = "SumerianProvider"

Const FLUSH_INTERVAL

FLUSH_INTERVAL: number = 5*1000

Const FLUSH_SIZE

FLUSH_SIZE: 100 = 100

Const HTTPS_PORT

HTTPS_PORT: "443" = "443"

Const HTTP_PORT

HTTP_PORT: "80" = "80"

Const Hub

Hub: HubClass = new HubClass('__default__')

Const IOT_SERVICE_NAME

IOT_SERVICE_NAME: "iotdevicegateway" = "iotdevicegateway"

Const Linking

Linking: object

Type declaration

Const MEMORY_KEY_PREFIX

MEMORY_KEY_PREFIX: "@MemoryStorage:" = "@MemoryStorage:"

Const MIME_MAP

MIME_MAP: object[] = [{ type: 'text/plain', ext: 'txt' },{ type: 'text/html', ext: 'html' },{ type: 'text/javascript', ext: 'js' },{ type: 'text/css', ext: 'css' },{ type: 'text/csv', ext: 'csv' },{ type: 'text/yaml', ext: 'yml' },{ type: 'text/yaml', ext: 'yaml' },{ type: 'text/calendar', ext: 'ics' },{ type: 'text/calendar', ext: 'ical' },{ type: 'image/png', ext: 'png' },{ type: 'image/gif', ext: 'gif' },{ type: 'image/jpeg', ext: 'jpg' },{ type: 'image/jpeg', ext: 'jpeg' },{ type: 'image/bmp', ext: 'bmp' },{ type: 'image/x-icon', ext: 'ico' },{ type: 'image/tiff', ext: 'tif' },{ type: 'image/tiff', ext: 'tiff' },{ type: 'image/svg+xml', ext: 'svg' },{ type: 'application/json', ext: 'json' },{ type: 'application/xml', ext: 'xml' },{ type: 'application/x-sh', ext: 'sh' },{ type: 'application/zip', ext: 'zip' },{ type: 'application/x-rar-compressed', ext: 'rar' },{ type: 'application/x-tar', ext: 'tar' },{ type: 'application/x-bzip', ext: 'bz' },{ type: 'application/x-bzip2', ext: 'bz2' },{ type: 'application/pdf', ext: 'pdf' },{ type: 'application/java-archive', ext: 'jar' },{ type: 'application/msword', ext: 'doc' },{ type: 'application/vnd.ms-excel', ext: 'xls' },{ type: 'application/vnd.ms-excel', ext: 'xlsx' },{ type: 'message/rfc822', ext: 'eml' }]

Const NON_RETRYABLE_EXCEPTIONS

NON_RETRYABLE_EXCEPTIONS: string[] = ['BadRequestException', 'SerializationException', 'ValidationException']

OS

OS: any

Const PREV_URL_KEY

PREV_URL_KEY: "aws-amplify-analytics-prevUrl" = "aws-amplify-analytics-prevUrl"

Const REMOTE_NOTIFICATION_RECEIVED

REMOTE_NOTIFICATION_RECEIVED: "remoteNotificationReceived" = "remoteNotificationReceived"

Const REMOTE_TOKEN_RECEIVED

REMOTE_TOKEN_RECEIVED: "remoteTokenReceived" = "remoteTokenReceived"

Const RESEND_LIMIT

RESEND_LIMIT: 5 = 5

Const RNPushNotification

RNPushNotification: any = NativeModules.RNPushNotification

Const SERVICE_NAME

SERVICE_NAME: "iotdevicegateway" = "iotdevicegateway"

Const SUMERIAN_SERVICE_NAME

SUMERIAN_SERVICE_NAME: "sumerian" = "sumerian"

Const Storage

Storage: StorageClass = _instance

Let _config

_config: any = null

Let _i18n

_i18n: any = null

Let Const _instance

_instance: XRClass = null

Const a

a: HTMLAnchorElement = JS.browserOrNode().isBrowser ? document.createElement('a') : null

Let analyticsConfigured

analyticsConfigured: boolean = false

Let authConfigured

authConfigured: boolean = false

Const cache

cache: object

Type declaration

Const components

components: (AuthenticatorIonicComponent | ConfirmSignInComponentIonic | GreetingComponentIonic | SignInComponentIonic | SignUpComponentIonic | RequireNewPasswordComponentIonic | PhotoPickerIonicComponent | S3AlbumComponentIonic | S3ImageComponentIonic | ChatbotComponentIonic)[] = [AuthenticatorIonicComponent,ConfirmSignInComponentIonic,ConfirmSignUpComponentIonic,ForgotPasswordComponentIonic,GreetingComponentIonic,SignInComponentIonic,SignUpComponentIonic,RequireNewPasswordComponentIonic,PhotoPickerIonicComponent,S3AlbumComponentIonic,S3ImageComponentIonic,ChatbotComponentIonic]

Const crypto

crypto: any = AWS['util'].crypto

Let dataMemory

dataMemory: object

Type declaration

Let endpointUpdated

endpointUpdated: boolean = false

Let initialEventSent

initialEventSent: boolean = false

Const instance

instance: Credentials = new Credentials(null)

Const lists

lists: MethodEmbed[] = []

Const logger

logger: any = new Logger('XR')

Const nativeMatches

nativeMatches: any = proto ? proto.matches ||proto.matchesSelector ||proto.webkitMatchesSelector ||proto.mozMatchesSelector ||proto.msMatchesSelector ||proto.oMatchesSelector : null

Const packageInfo

packageInfo: any = require("../../package.json")

Const proto

proto: any = JS.browserOrNode().isBrowser && window['Element']? window['Element'].prototype: null

Let store

store: object

provide an object as the in-memory cache

Type declaration

Const template

template: "<div class="amplify-form"><div class="form-header"><div class="form-title">{{ title }}</div></div><div class="form-body"><ng-content select="[form-body]"></ng-content></div><div class="form-footer"><ng-content select="[form-footer]"></ng-content></div></div>" = `<div class="amplify-form"><div class="form-header"><div class="form-title">{{ title }}</div></div><div class="form-body"><ng-content select="[form-body]"></ng-content></div><div class="form-footer"><ng-content select="[form-footer]"></ng-content></div></div>`

Const topicSymbol

topicSymbol: any = typeof Symbol !== 'undefined' ? Symbol('topic') : '@@topic'

Const url

url: any = require('url')

Const urlLib

urlLib: any = require('url')

Const waitForInit

waitForInit: any = new Promise((res, rej) => {if (!JS.browserOrNode().isBrowser) {logger.debug('not in the browser, directly resolved');return res();}const ga = window['gapi'] && window['gapi'].auth2 ? window['gapi'].auth2 : null;if (ga) {logger.debug('google api already loaded');return res();} else {setTimeout(() => {return res();},2000);}})

Functions

_isInteger

  • _isInteger(value: any): boolean

Const analyticsEvent

  • analyticsEvent(payload: any): void

authDecorator

  • authDecorator(authState: Subject<AuthState>): void

Const authEvent

  • authEvent(payload: any): void

browserClientInfo

  • browserClientInfo(): object | object

browserTimezone

  • browserTimezone(): string

browserType

  • browserType(userAgent: any): object

Private Const canonical_headers

  • canonical_headers(headers: any): string

Private Const canonical_request

  • canonical_request(request: any): string

check

Const clientInfo

  • clientInfo(): object
  • clientInfo(): object

closest

  • closest(element: any, selector: any, shouldCheckSelf?: boolean): any
  • Gets the closest parent element that matches the passed selector.

    Parameters

    • element: any

      The element whose parents to check.

    • selector: any

      The CSS selector to match against.

    • Default value shouldCheckSelf: boolean = false

      True if the selector should test against the passed element itself.

    Returns any

    The matching element or undefined.

Const credential_scope

  • credential_scope(d_str: any, region: any, service: any): string

decorateConfirmSignUp

  • decorateConfirmSignUp(authState: Subject<AuthState>): void

decorateSignIn

  • decorateSignIn(authState: Subject<AuthState>): void

decorateSignOut

  • decorateSignOut(authState: Subject<AuthState>): void

decorateSignUp

  • decorateSignUp(authState: Subject<AuthState>): void

delegate

  • delegate(ancestor: any, eventType: any, selector: any, callback: any, opts?: object): object
  • Delegates the handling of events for an element matching a selector to an ancestor of the matching element.

    Parameters

    • ancestor: any

      The ancestor element to add the listener to.

    • eventType: any

      The event type to listen to.

    • selector: any

      A CSS selector to match against child elements.

    • callback: any

      A function to run any time the event happens.

    • Default value opts: object = {}

      A configuration options object. The available options:

      - useCapture<boolean>: If true, bind to the event capture phase.
      - deep<boolean>: If true, delegate into shadow trees.
      

    Returns object

    The delegate object. It contains a destroy method.

dimToMake

  • dimToMake(dim: any): object

dimension

  • dimension(): object

dispatch

  • dispatch(element: any, eventType: any, evtName?: string, init_dict?: object): any
  • Dispatches an event on the passed element.

    Parameters

    • element: any

      The DOM element to dispatch the event on.

    • eventType: any

      The type of event to dispatch.

    • Default value evtName: string = "Event"
    • Default value init_dict: object = {}

    Returns any

    The return value of element.dispatchEvent, which will be false if any of the event listeners called preventDefault.

Const dispatchAnalyticsEvent

  • dispatchAnalyticsEvent(event: any, data: any): void

Const dispatchAuthEvent

  • dispatchAuthEvent(event: any, data: any): void

Const dispatchStorageEvent

  • dispatchStorageEvent(track: any, attrs: any, metrics: any): void

Const encrypt

  • encrypt(key: any, src: any, encoding?: any): any

getAttributes

  • getAttributes(element: any): object
  • Gets all attributes of an element as a plain JavaScriot object.

    Parameters

    • element: any

      The element whose attributes to get.

    Returns object

    An object whose keys are the attribute keys and whose values are the attribute values. If no attributes exist, an empty object is returned.

getByteLength

  • getByteLength(str: string): number

getCurrTime

  • getCurrTime(): number

getInstance

  • getInstance(context: any, methodName: any): MethodEmbed

Const getUrl

  • getUrl(): string

Private Const get_authorization_header

  • get_authorization_header(algorithm: any, access_key: any, scope: any, signed_headers: any, signature: any): string
  • Parameters

    • algorithm: any
    • access_key: any
    • scope: any
    • signed_headers: any
    • signature: any

    Returns string

Const get_signature

  • get_signature(signing_key: any, str_to_sign: any): any

Private Const get_signing_key

  • get_signing_key(secret_key: any, d_str: any, service_info: any): any

Const graphqlOperation

  • graphqlOperation(query: any, variables?: object): object
  • Parameters

    • query: any
    • Default value variables: object = {}

    Returns object

    • query: any
    • variables: object

Const hash

  • hash(src: any): any

includes

  • includes(ary: any, match: any): boolean

invalidParameter

  • invalidParameter(name: any): Error

isInteger

  • isInteger(value: any): boolean

listen

  • listen(authState: Subject<AuthState>): void

matches

  • matches(element: any, test: any): any
  • Tests if a DOM elements matches any of the test DOM elements or selectors.

    Parameters

    • element: any

      The DOM element to test.

    • test: any

      A DOM element, a CSS selector, or an array of DOM elements or CSS selectors to match against.

    Returns any

    True of any part of the test matches.

matchesSelector

  • matchesSelector(element: any, selector: any): any
  • Tests whether a DOM element matches a selector. This polyfills the native Element.prototype.matches method across browsers.

    Parameters

    • element: any

      The DOM element to test.

    • selector: any

      The CSS selector to test element against.

    Returns any

    True if the selector matches.

missingConfig

  • missingConfig(name: any): Error

parents

  • parents(ele: any): any[]
  • Returns an array of a DOM element's parent elements.

    Parameters

    • ele: any

    Returns any[]

    An array of all parent elemets, or an empty array if no parent elements are found.

parseUrl

  • parseUrl(u: any): any

Const parse_service_info

  • parse_service_info(request: any): object

Const sign

  • sign(request: any, access_info: any, service_info?: any): any
  • Sign a HTTP request, add 'Authorization' header to request param

    Parameters

    • request: any

      HTTP request object

      request: {
      method: GET | POST | PUT ...
      url: ...,
      headers: {
      header1: ...
      },
      data: data
      }
      
    • access_info: any

      AWS access credential info

      access_info: {
      access_key: ...,
      secret_key: ...,
      session_token: ...
      }
      
    • Default value service_info: any = null

    Returns any

    Signed HTTP request

Const signUrl

  • signUrl(urlToSign: String, accessInfo: any, serviceInfo?: any, expiration?: Number): any
  • Parameters

    • urlToSign: String
    • accessInfo: any
    • Optional serviceInfo: any
    • Optional expiration: Number

    Returns any

Const signed_headers

  • signed_headers(headers: any): string
  • List of header keys included in the canonical headers.

    Parameters

    • headers: any

    Returns string

Const storageEvent

  • storageEvent(payload: any): void

Private Const string_to_sign

  • string_to_sign(algorithm: any, canonical_request: any, dt_str: any, scope: any): string
  • Parameters

    • algorithm: any
    • canonical_request: any
    • dt_str: any
    • scope: any

    Returns string

Object literals

Const AppState

AppState: object

addEventListener

  • addEventListener(action: any, handler: any): void

Const Constants

Constants: object

userAgent

userAgent: any = Platform.userAgent

Const LOG_LEVELS

LOG_LEVELS: object

DEBUG

DEBUG: number = 2

ERROR

ERROR: number = 5

INFO

INFO: number = 3

VERBOSE

VERBOSE: number = 1

WARN

WARN: number = 4

Const Platform

Platform: object

isReactNative

isReactNative: boolean = false

navigator

navigator: null = null

product

product: string = ""

userAgent

userAgent: string = `aws-amplify/${packageInfo.version} js`

Const defaultConfig

defaultConfig: object

Default cache config

capacityInBytes

capacityInBytes: number = 1048576

defaultPriority

defaultPriority: number = 5

defaultTTL

defaultTTL: number = 259200000

itemMaxSize

itemMaxSize: number = 210000

keyPrefix

keyPrefix: string = "aws-amplify-cache"

storage

storage: any = new StorageHelper().getStorage()

warningThreshold

warningThreshold: number = 0.8

Const defaultOpts

defaultOpts: object

enable

enable: boolean = false

events

events: string[] = ['click']

getUrl

getUrl: getUrl

provider

provider: string = "AWSPinpoint"

selectorPrefix

selectorPrefix: string = "data-amplify-analytics-"

Const trackers

trackers: object

event

event: any = EventTracker

pageView

pageView: any = PageViewTracker

session

session: any = SessionTracker