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 });};
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
Upgrade to the latest Amplify library using the following command:
npm install aws-amplify@6
The aws-amplify
package in v6 includes the categories below:
- Auth
- API
- Storage
- Analytics
- DataStore
- In-App Messaging
If you previously listed @aws-amplify
namespaced packages for the above categories as dependencies in your package.json
, you will need to remove them to avoid dependency duplication.
If you would like to use Geo, Predictions, PubSub, or Interactions you will need to install those packages separately. (see category-specific migration instructions)
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)
- Analytics - Storing analytics data (Kinesis Firehose)
- Analytics - Personalized recommendations
- Interactions - Set up Amplify Interactions
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.
Predictions
To use Predictions in v6, you will first need to install the category as a separate dependency using the below command:
npm install @aws-amplify/predictions
In v6, the provider will be included by default and you are no longer required to call Predictions.addPluggable
to use this category. Otherwise, Predictions operates in the same way as before. Use the switcher below to see the differences between v5 and v6:
import { Amplify } from 'aws-amplify';import { Predictions, AmazonAIPredictionsProvider} from '@aws-amplify/predictions';import awsconfig from './aws-exports';
Amplify.configure(awsconfig);Predictions.addPluggable(new AmazonAIPredictionsProvider());
const translateText = async ({ textToTranslate }) => { const result = await Predictions.convert({ translateText: { source: { text: textToTranslate } } });}
import { Predictions } from '@aws-amplify/predictions';import { Amplify } from 'aws-amplify';import amplifyconfig from './amplifyconfiguration.json';
Amplify.configure(amplifyConfig);
const translateText = async ({ textToTranslate }) => { const result = await Predictions.convert({ translateText: { source: { text: textToTranslate } } });}
For a deeper look at Predictions functionality in v6, check out our Predictions 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.