Enhancements for Amplify's Generation 2
If you want to utilize cookies instead of the default storage mechanism in Amplify Gen 2, you can simply add ssr: true
to the library options when configuring Amplify.
Amplify.configure(outputs, {
ssr: true // required when using Amplify with Next.js
});
Please Note: To make use of the Amplify library on the client side within a Next.js application, it is necessary to specify ssr
as true
while invoking Amplify.configure
. This enables the Amplify library to store tokens in the cookie store of a browser, ensuring that cookies are sent along with requests to your Next.js server for authentication purposes.
For more information, visit - Configure Amplify library for client-side usage
Options for Enhancing Amplify Generation 1
In order to customize where and how tokens are persisted in your application with Amplify Gen 1, you have the freedom to update the storage mechanism. By default, tokens are stored in localStorage
, but you also have the option to import sessionStorage
, sharedInMemoryStorage
, or CookieStorage
.
To store tokens in cookies, include the following line of code.
cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());
Here is a full example of the code implementation.
import { Amplify, type ResourcesConfig } from 'aws-amplify';
import { CookieStorage } from 'aws-amplify/utils';
import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const authConfig: ResourcesConfig['Auth'] = {
Cognito: {
userPoolId: 'your_user_pool_id',
userPoolClientId: 'your_user_pool_client_id'
}
};
Amplify.configure({
Auth: authConfig
});
cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());
To delve deeper into this topic, check out Understand token management options.