User sessions
Amplify backend auth creates a session when a user signs in. The client SDK uses it to keep the user signed in until the session ends. To read the signed-in user in server code, see Server-side rendering.
Session expiration
A session lasts 7 days. Auth extends the expiry of a session when it’s used, at most once a day.
To change these times, set the session object of backend.auth in your amplify.jsonc file. Values are in seconds.
// amplify.jsonc { "backend": { "auth": { "appName": "My App", "emailAndPassword": { "enabled": true }, "session": { "expiresIn": 1209600, // optional: how long a session lasts. 300 to 31536000, default 604800 (7 days) "updateAge": 86400 // optional: how often using the session extends it. 0 (every request) to 31536000, default 86400 (1 day) } } } }
For how the auth block works, see Auth configuration.
Session freshness
Unlinking a provider and listing a user’s sessions need a fresh session, one that started less than 1 day ago. An older session gets SESSION_NOT_FRESH. To change that time, set freshAge. To turn off the check, set freshAge to 0.
"session": { "freshAge": 300 } // optional: 0 to 31536000 seconds, default 86400 (1 day)
Get the session
To get the signed-in user, call getSession. The session is null when no user is signed in. The session that getSession returns can come from the browser’s cache. To re-read it from the backend, call backend.auth.refetch(). Make access decisions in your RLS policies or in server code with createServerAuth(…).getUser().
Browser code gets AMPLIFY_BACKEND_URL and AMPLIFY_BACKEND_PUBLISHABLE_KEY only when your framework inlines them as your app builds, such as with a Vite define. For more information, see the client SDK README
import { createClient } from '@aws-amplifygen3/backend-client-js' const backend = createClient(import.meta.env.AMPLIFY_BACKEND_URL, import.meta.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY) const { data: { session } } = await backend.auth.getSession() // session?.user has id, email, name and emailVerified
Tokens for data API calls
The SDK exchanges the session for a JSON Web Token (JWT) that lasts 15 minutes, and sends it in the Authorization: Bearer header of each data API call. When the token expires, the SDK gets a new one from the session before the next query. Your app stores no token and no refresh token.
On a deployed backend, if the session ended elsewhere, the tab’s next call fails with 401
invalid_credential. The SDK then signs the tab out, and later calls use the anon role. On the local backend the token keeps working until it expires; the SDK then finds the session gone, signs the tab out and sends later calls as anon, with no 401.
Sign users out
To sign a user out, call signOut. It ends the session.
const { error } = await backend.auth.signOut()
If signOut returns an error, the SDK still removes the session from this browser, but the session can stay active on the backend until it expires. The SDK has no session left to send, so a second signOut or a revokeSessions call can’t end it. To end it, call revokeUserSessions from server code. For more information, see Manage users.
On a deployed backend, the user’s token stops working within 30 seconds. Banning or removing the user does the same. A request with the token then gets 401 with the message invalid credential. A request with an expired token gets a different message: The bearer token is not valid for this backend. On the local backend, the token works until it expires.
A password reset also ends all of the user’s sessions.
Revoke sessions
A signed-in user can list and end their own sessions with the following client SDK calls:
-
auth.listSessions()– Returns the user’s sessions. It needs a fresh session, so it fails withSESSION_NOT_FRESHonce the session is older thanfreshAge. -
auth.revokeSession({ token })– Ends one session. Pass the session’stokenfromlistSessions(). -
auth.revokeOtherSessions()– Ends every session except the current one. -
auth.revokeSessions()– Ends every session, including the current one.
const { data: { sessions } } = await backend.auth.listSessions() await backend.auth.revokeOtherSessions()
To sign a user out of one session from your server, call revokeSession on the server admin client. To sign them out on every device, call revokeUserSessions. For more information, see Manage users.
Cookie mode and token mode
The SDK keeps a browser session in one of two modes. It picks the mode from where your backend runs.
| Cookie mode | Token mode | |
|---|---|---|
|
When |
Your website and backend are on the same scheme and host name, on any port, such as |
Your website and backend are on different hosts, as in every deployed app |
|
Where the session is kept |
The backend’s HTTP-only cookie |
Browser storage. The SDK sends it in a request header. |
|
What your server code can read |
The session, from the request’s cookies |
Nothing, unless you set |
By default, the SDK uses cookie mode when your website and backend are on the same scheme and host name, such as localhost with the local backend. A deployed app’s backend is on another host, so the app uses token mode. To the browser, the backend’s cookie is a third-party cookie, and browsers can block third-party cookies. Token mode sends no cookies to the backend. Test your session code in a deployed environment too, such as preview.
To set the mode yourself, create the client with auth: { authMode: 'token' } or auth: { authMode: 'cookie' }. Don’t set 'cookie' in a deployed app: its backend is on another host, so the cookie is third-party and browsers can block it. In Node, the SDK uses cookie mode, and each client has its own session.
Choose where token mode keeps the session
Set sessionStore when you create the client:
const backend = createClient(url, publishableKey, { auth: { sessionStore: 'localStorage', // default: shared by your app's tabs, kept on reload // 'sessionStorage': one tab // 'memory': lost when a page loads // 'cookie': a cookie on your app's own host, which your server can read // or your own object with synchronous getItem, setItem and removeItem }, })
An async store isn’t supported. If the browser blocks the store, as in private browsing, the SDK keeps the session in memory for that page and logs a warning. Tabs that share the session, with 'localStorage', 'cookie', or cookie mode, see each other’s sign-in, sign-out, and profile changes. To turn that off, set auth: { crossTabSync: false }.
Any script on your site can read a session that token mode keeps, and use it until it expires or the user signs out. A 'cookie' session isn’t HTTP-only either, and it reaches your server with each request, so don’t log request cookies.
Create the client on your root page
Social sign-in, email links, and the managed sign-in page take the user away from your page. When the user finishes signing in, the browser returns to the root of the callback URL’s origin with a code. The code works once, within 2 minutes. The client on your root page exchanges the code, then opens the page that the callback URL named. If the code is redeemed later, the user stays signed out. The SDK still opens the page and returns no error. It logs only the console warning the sign-in code on this page was not redeemed. So check for a session on that page, and send a signed-out user back to sign in. In token mode, if your root page doesn’t create the client, the user stays signed out. With sessionStore: 'memory', the client changes the address to that page without loading it. Your router must then show the page for the current address.
Errors
| Error | When | What to do |
|---|---|---|
|
|
A token’s session ended |
Sign the user in again |
|
|
A sensitive action on a session older than |
Sign the user in again |
For instructions on installing and creating the client, see the client SDK README