Migrate from Amplify JavaScript v5 to v6
This migration guide will help you upgrade your Amplify JavaScript project from v5 to v6. In order to provide you with a cleaner experience, better typings, improved support for NextJS, and improved tree-shaking leading to a much smaller bundle-size, we made the following changes for v6:
- We have transitioned to an approach where you only import the features you need from each of our categories.
- Most API’s now use named params instead of positional params, allowing for cleaner and more consistent typing.
- We have enabled typescript strict mode on all categories and have added typing to help make it easier to connect your backend resources if you have chosen not to use the Amplify CLI.
Below is an example of how you would have previously interacted with the Amplify JavaScript library in v5.
import { CognitoUser } from '@aws-amplify/auth';import { Auth } from 'aws-amplify';
const handleSignIn = async ({ username, password}: { username: string; password: string;}) => { const user: CognitoUser = Auth.signIn(username, password);};
The following is an example of how you would accomplish the same functionality with v6, using our new imports and API surface.
import { signIn } from 'aws-amplify/auth';
const handleSignIn = async ({ username, password}: { username: string; password: string;}) => { const { isSignUpComplete, userId, nextStep } = signIn({ username, password });};
Changes to React Native
As part of the updates to Amplify JavaScript v6, we also re-evaluated our strategy for how we can best support React Native going forward. This has been an ongoing effort ever since we introduced our updated Push Notification experience in v5 and is something we will continue to evolve along with the ever-changing React Native ecosystem.
@aws-amplify/react-native
We have introduced a new package - @aws-amplify/react-native
- to encompass the core requirements for using Amplify JavaScript v6 in a React Native environment. This package is a new requirement which allows us to:
- Remove the dependency on the
amazon-cognito-identity-js
package by moving core native Amplify functionality previously vended by this package into@aws-amplify/react-native
. - Automatically install JavaScript-only (i.e. non-native module dependencies) polyfills required by Amplify as transitive dependencies, no longer requiring extra steps from you.
- Automatically import all required polyfills, no longer requiring you to take extra steps to include import statements at the top of your application entry point.
Native modules required by Amplify such as
@react-native-async-storage/async-storage
orreact-native-get-random-values
still need to be installed separately as they need to be linked with React Native
Instructions for React Native version 0.72 and below
@aws-amplify/react-native
requires a minimum iOS deployment target of 13.0
if you are using react-native
version less than or equal to 0.72
. Open the Podfile located in the ios directory and update the target
value:
- platform :ios, min_ios_version_supported + platform :ios, 13.0
Dropping support for Expo Go
With the goal of providing more idiomatic native functionality to your React Native application, Expo Go will no longer be supported in v6.
Per the Expo docs:
The Expo Go app is a great tool to get started. It exists to help developers quickly get projects off the ground, experiment with ideas (such as on Snack), and share their work with minimal friction. Expo Go makes this possible by including a feature-rich native runtime made up of every module in the Expo SDK, so all you need to do to use a module is install the package and reload your app.
The tradeoff is that Expo Go does not allow you to add custom native code. You can only use native modules built into the Expo SDK. Many great libraries are available outside of the Expo SDK, and you may even want to build your native library. You can leverage these libraries with development builds or using prebuild to generate native projects, or both. You can also continue using EAS Build to release your app as no changes are required.
A key part of Amplify's React Native strategy going forward is to reduce our reliance on third-party native modules. While third-party native modules are a mainstay of the React Native ecosystem, we believe the flexibility of building more native modules tailored to the specific needs of our customers will allow us to most quickly deliver value to them in the long run. As a result of now requiring native modules not available through the Expo SDK, Expo Go is not supported in v6 but you should still be able to use Expo.
Step 1: Upgrade your dev environment
In order to use Amplify JavaScript v6, you will need to make sure you are using the following versions in your development environment:
Step 2: Upgrade your Amplify project dependencies
To upgrade React Native projects that do not utilize aws-amplify-react-native
, remove amazon-cognito-identity-js
from the project package.json and install @aws-amplify/react-native
.
Then upgrade/install the necessary dependencies using the following command:
npm install aws-amplify@6 @aws-amplify/react-native @react-native-community/netinfo @react-native-async-storage/async-storage react-native-get-random-values
Note that v6 supports react-native v0.70+, so if you prefer manually upgrading dependencies double-check the version of react-native in your package.json file.
Step 3: Upgrade Amplify CLI version and configuration file
If you created your project with Amplify CLI version < 12.5.1, upgrade your CLI version and regenerate your configuration file using the scripts below.
amplify upgradeamplify push
This will generate a new configuration file called amplifyconfiguration.json
Wherever you called Amplify.configure({ aws-exports });
previously (usually in the root of your project) update your code as shown below
V5
import awsconfig from './aws-exports';
Amplify.configure(awsconfig);
V6
import amplifyconfig from './amplifyconfiguration.json';
Amplify.configure(amplifyconfig);
If you have previously configured Amplify by passing the configuration object literal when calling the Amplify.configure()
function, you can now configure Amplify manually with type safety. Please refer to the documentation of each category that you are using for migration.
- Authentication - Set up and configure Amplify Auth - see Existing Resources tab
- API (GraphQL) - Configure the Amplify Library - see Existing AppSync GraphQL API tab
- API (REST) - Use existing AWS resources
- API (REST) - Define authorization rules
- Storage - Use existing AWS resources
- Analytics - Use existing AWS resources
- Analytics - Streaming analytics data (Kinesis)
- Interactions - Set up Amplify Interactions
Remove polyfill imports
For React Native applications, polyfill imports should no longer need to be added to your application's entry point file as they are imported by the @aws-amplify/react-native
package.
// Example index.js- import 'react-native-get-random-values';- import 'react-native-url-polyfill/auto';
Step 4: Update category usage
Auth
As of v6 of Amplify, you will now import the functional API’s directly from the aws-amplify/auth
path as shown below. Use the switcher below to see the differences between v5 and v6:
import { Auth } from 'aws-amplify';
async function signIn() { try { const user = await Auth.signIn(username, password); } catch (error) { console.log('error signing in', error); }}
async function signOut() { try { await Auth.signOut(); } catch (error) { console.log('error signing out: ', error); }}
import { signIn, signOut } from 'aws-amplify/auth';
async function handleSignIn({ username, password }) { try { const { isSignedIn, nextStep } = await signIn({ username, password }); } catch (error) { console.log('error signing in', error); }}
async function handleSignOut() { try { await signOut(); } catch (error) { console.log('error signing out: ', error); }}
For a deeper look at v6 Auth functionality, check out our Authentication category documentation.
Analytics
As of v6 of Amplify, you will now import the functional API’s directly from the aws-amplify/analytics
path as shown below. Note that in v6, the provider is determined by import path. The functions exported from aws-amplify/analytics
use AWS Pinpoint. Use the switcher below to see the differences between v5 and v6:
import { Analytics } from 'aws-amplify';
Analytics.record({ name: 'albumVisit', attributes: { genre: '', artist: '' }, metrics: { minutesListened: 30 }});
Analytics.autoTrack('session', { enable: true, attributes: { customizableField: 'attr' }, provider: 'AWSPinpoint'});
import { record, configureAutoTrack } from 'aws-amplify/analytics';
record({ name: 'albumVisit', attributes: { genre: '', artist: '' }, metrics: { minutesListened: 30 }});
configureAutoTrack({ enable: true, type: 'session', options: { attributes: { customizableField: 'attr' } }});
For a deeper look at V6 Analytics functionality, check out our Analytics category documentation.
API (GraphQL)
As of v6 of Amplify, you will now import a function called generateClient
from the aws-amplify/api
path and use the client
returned from that method to perform graphql operations as shown below. Use the switcher below to see the differences between v5 and v6:
import { API, graphqlOperation } from 'aws-amplify';import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
const todo = { name: 'My first todo', description: 'Hello world!'};
/* create a todo */const newTodo = await API.graphql( graphqlOperation(createTodo, { input: todo }));
/* update a todo */const updatedTodo = await API.graphql( graphqlOperation(updateTodo, { input: { id: newTodo.id, name: 'Updated todo info' } }));
/* delete a todo */await API.graphql( graphqlOperation(deleteTodo, { input: { id: newTodo.id } }));
import { generateClient } from 'aws-amplify/api';import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
const client = generateClient();
const todo = { name: 'My first todo', description: 'Hello world!'};
/* create a todo */const newTodo = await client.graphql({ query: createTodo, variables: { input: todo }});
/* update a todo */const updatedTodo = await client.graphql({ query: updateTodo, variables: { input: { id: newTodo.id, name: 'Updated todo info' }}});
/* delete a todo */const deletedTodo = await client.graphql({ query: deleteTodo, variables: { input: { id: newTodo.id } }});
For a deeper look at how the GraphQL API functionality in V6, check out our API (GraphQL) category documentation.
API (Rest)
As of v6 of Amplify, you will now import the functional API’s directly from the aws-amplify/api
path as shown below. Use the switcher below to see the differences between v5 and v6:
import { Amplify, API } from 'aws-amplify';
/* fetch data */async function getData() { const apiName = 'MyApiName'; const path = '/path'; const options = { headers: {} // OPTIONAL };
return await API.get(apiName, path, options);}
/* update data */async function postData() { const apiName = 'MyApiName'; const path = '/path'; const options = { body: { name: 'My first todo', message: 'Hello world!' }, headers: {} // OPTIONAL };
return await API.post(apiName, path, options);}
postData();
/* delete data */async function deleteData() { const apiName = 'MyApiName'; const path = '/path'; const options = { headers: {} // OPTIONAL }; return await API.del(apiName, path, options);}
deleteData();
import { get, put, del } from 'aws-amplify/api';
/* fetch data */async function getTodo() { const apiName = 'MyApiName'; const path = '/path'; const options = { body: { name: 'My first todo', message: 'Hello world!' }, headers: {} // OPTIONAL };
const restOperation = get({ apiName, path, options }); return await restOperation.response;}
/* update data */async function updateTodo() { const apiName = 'MyApiName'; const path = '/path'; const options = { body: { name: 'My first todo', message: 'Hello world!' }, headers: {} // OPTIONAL };
const restOperation = put({ apiName, path, options }); return await restOperation.response;}
/* delete data */async function deleteTodo() { const apiName = 'MyApiName'; const path = '/path'; const options = { headers: {} // OPTIONAL };
const restOperation = del({ apiName, path, options }); return await restOperation.response;}
For a deeper look at how the REST API functionality in V6, check out our API (REST) category documentation.
In-App Messaging
As of v6 of Amplify, you will now import the functional API’s directly from the aws-amplify/in-app-messaging
path as shown below. Use the switcher below to see the differences between v5 and v6:
import { Notifications } from 'aws-amplify';
const { InAppMessaging } = Notifications;InAppMessaging.syncMessages();
const sendEvent = (eventName: string) => { InAppMessaging.dispatchEvent({ name: eventName });}
import { dispatchEvent, initializeInAppMessaging, syncMessages} from 'aws-amplify/in-app-messaging';
initializeInAppMessaging();syncMessages();
const sendEvent = (eventName: string) => { dispatchEvent({ name: eventName });}
For a deeper look at In App Messaging functionality in v6, check out our In App Messaging category documentation.
Interactions
To use Interactions in v6, you will first need to install the category as a separate dependency using the below command:
npm install @aws-amplify/interactions
In v6, the AWSLexV2Provider
provider will be included by default and you are no longer required to call Amplify.addPluggable
. It is also recommended to integrate your App with AWS LexV2, as the default module exports are associated with AWS LexV2 APIs. Interactions operates in the same way as before, however, the configuration structure has changed somewhat. Use the switcher below to see the differences between v5 and v6:
import { Amplify } from 'aws-amplify';import { AWSLexV2Provider } from '@aws-amplify/interactions';import awsconfig from './aws-exports';
Amplify.configure(awsconfig);
Amplify.addPluggable(new AWSLexV2Provider());const interactionsConfig = { Interactions: { bots: { my_v2_bot: { name: '<V2BotName>', aliasId: '<V2BotAliasId>', botId: '<V2BotBotId>', localeId: '<V2BotLocaleId>', region: '<V2BotRegion>', providerName: 'AWSLexV2Provider', }, } }}
Amplify.configure(interactionsConfig);
import { Amplify } from 'aws-amplify';import amplifyconfig from './amplifyconfiguration.json';
Amplify.configure(amplifyconfig);
const interactionsConfig = { LexV2: { '<V2BotName>': { aliasId: '<V2BotAliasId>', botId: '<V2BotBotId>', localeId: '<V2BotLocaleId>', region: '<V2BotRegion>' } }}
Amplify.configure({ ...Amplify.getConfig(), Interactions: interactionsConfig});
For a deeper look at Interactions functionality in v6, check out our Interactions category documentation.
PubSub
As of v6 of Amplify, you will now import the functional API’s directly from the aws-amplify/pubsub
path as shown below. Use the switcher below to see the differences between v5 and v6:
import { Amplify, PubSub } from 'aws-amplify';import { AWSIoTProvider } from '@aws-amplify/pubsub';
// Apply plugin with configurationAmplify.addPluggable( new AWSIoTProvider({ aws_pubsub_region: '<YOUR-IOT-REGION>', aws_pubsub_endpoint: 'wss://xxxxxxxxxxxxx.iot.<YOUR-IOT-REGION>.amazonaws.com/mqtt' }));
// Step 1 - Create IAM policies for AWS IoT (see v5 docs)
// Step 2 - Attach your policy to your Amazon Cognito Identity ID
Auth.currentCredentials().then((info) => { const cognitoIdentityId = info.identityId;});
aws iot attach-policy --policy-name 'myIoTPolicy' --target '<YOUR_COGNITO_IDENTITY_ID>'
// Step 3 - Allow Amazon Cognito Authenticated Role to access IoT Services
import { Amplify } from 'aws-amplify';import { PubSub } from '@aws-amplify/pubsub';
// Apply plugin with configurationconst pubsub = new PubSub({ region: '<YOUR-IOT-REGION>', endpoint: 'wss://xxxxxxxxxxxxx.iot.<YOUR-IOT-REGION>.amazonaws.com/mqtt'});
// Step 1 - Create IAM policies for AWS IoT (see v5 docs)
// Step 2 - Attach your policy to your Amazon Cognito Identity ID
import { fetchAuthSession } from 'aws-amplify/auth';fetchAuthSession().then((info) => { const cognitoIdentityId = info.identityId;});
aws iot attach-policy --policy-name 'myIoTPolicy' --target '<YOUR_COGNITO_IDENTITY_ID>'
// Step 3 - Allow Amazon Cognito Authenticated Role to access IoT Services
For a deeper look at PubSub functionality in V6, check out our PubSub category documentation.
Storage
As of v6 of Amplify, you will now import the functional API’s directly from the aws-amplify/storage
path as shown below. Use the switcher below to see the differences between v5 and v6:
import { Storage } from 'aws-amplify';
// Upload a file with access level `public`const result = await Storage.put('test.txt', 'Hello', { level: 'public',});
// Generate a file download url with check if the file exists in the S3 bucketconst url = await Storage.get('filename.txt', { validateObjectExistence: true});
import { getUrl, uploadData } from 'aws-amplify/storage';
// Upload a file with access level `guest` as the equivalent of `public` in v5const result = await uploadData({ key: 'test.txt', data: 'Hello', options: { accessLevel: 'guest' }}).result;
// Generate a file download url with check if the file exists in the S3 bucketconst url = await getUrl({ key: 'filename.txt', options: { validateObjectExistence: true },});
For a deeper look at how the Storage functionality in V6, check out our Storage category documentation.
Utilities
As of v6 of Amplify, you will now import utility classes and instances from the aws-amplify/utils
path as shown below. Use the switcher below to see the differences between v5 and v6:
import { ServiceWorker, Cache, Hub, I18n, Logger} from 'aws-amplify';
// Service Worker const serviceWorker = new ServiceWorker();
// Cache Cache.setItem(key, value, [options]);
// Hub (Listening for messages) class MyClass { constructor() { Hub.listen('auth', (data) => { const { payload } = data; this.onAuthEvent(payload); console.log('A new auth event has happened: ', data.payload.data.username + ' has ' + data.payload.event); }) }
onAuthEvent(payload) { // ... your implementation }}
// Internationalization I18n.setLanguage('fr');
// Logger const logger = new Logger('foo');
logger.info('info bar'); logger.debug('debug bar'); logger.warn('warn bar'); logger.error('error bar');
import { ServiceWorker, Cache, Hub, I18n, ConsoleLogger} from 'aws-amplify/utils';
// Service Worker const serviceWorker = new ServiceWorker();
// Cache Cache.setItem(key, value, [options]);
// Hub (Listening for messages) class MyClass { constructor() { Hub.listen('auth', (data) => { const { payload } = data; this.onAuthEvent(payload); console.log('A new auth event has happened: ', data.payload.data.username + ' has ' + data.payload.event); }) }
onAuthEvent(payload) { // ... your implementation } }
// Internationalization I18n.setLanguage('fr');
// Console Logger const logger = new ConsoleLogger('foo');
logger.info('info bar'); logger.debug('debug bar'); logger.warn('warn bar'); logger.error('error bar');
For a deeper look at v6 Utilities, check out our Utilities documentation.