Front-End Web & Mobile

AWS Amplify adds support for custom attributes in Amazon Cognito user pools

An Amazon Cognito user pool is a user directory for your web, mobile, or other applications.  In addition to the normal things you’d expect to store in an Amazon Cognito user pool (like a user name, email address, or phone number), you can also configure the user pool to hold any other information that you want through custom attributes.  With the latest AWS Amplify release, we’ve added the ability to store and retrieve custom attributes in your Amazon Cognito user pool.

When would this feature be useful? Imagine that you’re building an application for an ice cream shop. In your customer database, you want to make sure that you know the favorite ice cream type of each user. When a new customer signs up, you could ask them this information and add it to their profile. From then on, their favorite ice cream type would be easily accessible, along with the rest of their user profile!

To create a custom attribute during your sign-up process, add it to the attributes field of the signUp method of the Auth class:

Auth.signUp({
    'username': 'jdoe',
    'password': 'mysecurepassword#123',
    'attributes': {
        'email': 'me@domain.com',
        'phone_number': '+12135555555',
        'custom:favorite_flavor': 'Cookie Dough'  // custom attribute, not standard
    }
});

You can call Auth.currentUserInfo() to retrieve the profile of the user, which includes all the attributes.  For example, to access the user’s favorite ice cream flavor in your web or mobile app:

try {
  const currentUserInfo = await Auth.currentUserInfo()
  const favoriteFlavor = currentUserInfo.attributes['custom:favorite_flavor']
} catch (err) {
  console.log('error fetching user info: ', err);
}

You can also update a custom attribute at any time.  Use the Auth.updateUserAttributes() method:

const user = await Auth.currentAuthenticatedUser();
const result = await Auth.updateUserAttributes(user, {
    'custom:favorite_flavor': 'Strawberry'
});

To learn more about AWS Amplify, check out the developer documentation.