# Limit How Many Devices a User Can Log In From

Learn how to cap the number of devices a user can stay logged in on at the same time.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

FusionAuth has no built-in limit on concurrent sessions. You can build one with refresh tokens, which FusionAuth issues once per login on each browser or device. Count a user's refresh tokens for an Application, and act when the count reaches your limit. A user who logs in from Chrome and Firefox on one computer has two sessions.

Choose what happens when a user goes over the limit:

| Outcome | How | Tradeoff |
| --- | --- | --- |
| Block the new login | A `user.login.success` webhook returns an error. | Simple. The user has to find and log out of another device, and the error message applies to every failed webhook. |
| Let the user pick a session to end | Middleware in your application checks the count after login and shows a list of sessions. | More code. The user stays in control, and each request makes an extra API call. |

Both approaches require [centralized sessions](https://fusionauth.io/docs/authentication/sessions/centralized-sessions.md). Each login must create a refresh token, and each logout must revoke the refresh token. Otherwise, logged out devices still count toward the limit.

## Prerequisites

*   An Application with **Generate refresh tokens** turned on and the `Refresh Token` grant enabled, on the OAuth tab.
*   A login request that includes the `offline_access` scope.
*   A logout route that revokes the session's refresh token. For an example, see [Log Out of One Device](https://fusionauth.io/docs/authentication/sessions/centralized-sessions.md#log-out-of-one-device).
*   An API key with `GET` and `DELETE` permissions on `/api/jwt/refresh`.

## Count a User's Sessions

Call the [Retrieve Refresh Tokens API](https://fusionauth.io/docs/apis/jwt/retrieve-refresh-tokens.md) with the user's Id. The response includes refresh tokens for every Application, plus the user's [SSO session](https://fusionauth.io/docs/authentication/sessions/how-sessions-work.md#the-sso-session), which has no **`applicationId`**. Keep only the tokens for your Application:

Count the user's sessions for one Application

```typescript
const { refreshTokens = [] } = (await apiClient.retrieveRefreshTokens(event.user.id)).response;
// the SSO session and other applications' tokens don't count
const activeSessionCount = refreshTokens.filter((token) => token.applicationId === clientId).length;
```

## Block the New Login

FusionAuth sends the `user.login.success` event after the user enters valid credentials and before FusionAuth completes the login. When the webhook transaction requires the webhook to succeed, a non-`2xx` response stops the login.

1.  Navigate to Tenants -> Your Tenant -> Webhooks . Enable `user.login.success`, and set the transaction level for the event to `Any single webhook must succeed`.
    
2.  Navigate to Settings -> Webhooks and add a webhook. Set **URL** to your endpoint, such as `https://app.example.com/user-login-success`, and select `user.login.success`. In production, secure the webhook. For more information, see [Secure Webhooks](https://fusionauth.io/docs/events/webhooks/securing.md).
    
3.  In the endpoint, ignore events for other Applications, count the sessions, and return `403` when the user is at the limit:
    
    Block a login over the limit
    
    ```typescript
    app.post('/user-login-success', async (req, res) => {
      const event = req.body.event as UserLoginSuccessEvent;
      if (event.applicationId !== clientId || !event.user?.id) {
        res.sendStatus(200);
        return;
      }
    
      const { refreshTokens = [] } = (await apiClient.retrieveRefreshTokens(event.user.id)).response;
      // the SSO session and other applications' tokens don't count
      const activeSessionCount = refreshTokens.filter((token) => token.applicationId === clientId).length;
    
      // a non-2xx response stops the login when the webhook transaction requires success
      if (activeSessionCount >= maxDeviceCount) {
        console.log(`blocked login for user ${event.user.id}: ${activeSessionCount} of ${maxDeviceCount} sessions in use`);
        res.sendStatus(403);
        return;
      }
      res.sendStatus(200);
    });
    ```
    

FusionAuth shows the user a generic webhook error. To explain the limit, edit the `[WebhookTransactionException]` message in your theme's messages. For more information, see [Theme Localization](https://fusionauth.io/docs/theme/localization.md). The message applies to every webhook failure during a transaction, so reword the message to cover your other webhooks too.

To test the limit, log in as the same user from more browsers or private windows than the limit allows.

## Let the User Pick a Session to End

The session picker always lets the login finish. Your application then checks the session count on each protected request. When the user is over the limit, your application shows the other sessions and revokes the ones the user picks.

1.  Shorten the access token lifetime. A revoked refresh token doesn't end the access token that the other device already holds. Set **JWT duration** on the Application's JWT tab to a few minutes, such as `300` seconds, so the other device loses access soon after you revoke the session.
    
2.  Add middleware after your authentication middleware. The middleware lists the user's other sessions for the Application and redirects to a session picker when the count reaches the limit. The session list leaves out the current session, so the user can't end the session in use:
    
    Check the session count on each request
    
    ```typescript
    interface Device {
      id: string;
      deviceName: string;
      startInstant: string;
      ipAddress: string;
    }
    
    async function checkDeviceLimit(req: Request, res: Response, next: NextFunction) {
      const otherDevices = await getActiveDeviceList(req, res);
      if (otherDevices.length >= maxDeviceCount) {
        res.redirect(302, '/device-limit');
        return;
      }
      next();
    }
    
    // the user's other sessions for this application, without token values
    async function getActiveDeviceList(req: Request, res: Response): Promise<Device[]> {
      const currentRefreshTokenId = req.cookies[userToken]?.refresh_token_id;
      const { refreshTokens = [] } = (await apiClient.retrieveRefreshTokens(res.locals.userId)).response;
      return refreshTokens
        .filter((t) => t.applicationId === clientId && t.id !== currentRefreshTokenId)
        .map((t) => ({
          id: t.id as string,
          deviceName: t.metaData?.device?.name ?? 'Unknown device',
          startInstant: new Date(t.startInstant as number).toUTCString(),
          ipAddress: t.metaData?.device?.lastAccessedAddress ?? ''
        }));
    }
    ```
    
3.  Render the list on the picker page, with the device name, start time, and IP address from each refresh token. When the user submits the form, revoke each selected refresh token with the [Revoke Refresh Tokens API](https://fusionauth.io/docs/apis/jwt/revoke-refresh-tokens.md):
    
    Revoke the selected sessions
    
    ```typescript
    app.post("/device-limit", validateUserToken, async (req, res) => {
      const refreshTokenIds: string[] = [].concat(req.body.deviceIds ?? []);
      if (refreshTokenIds.length === 0) {
        res.redirect(302, '/device-limit');
        return;
      }
    
      // only revoke tokens that belong to this user and application
      const ownDeviceIds = new Set((await getActiveDeviceList(req, res)).map((device) => device.id));
      for (const refreshTokenId of refreshTokenIds.filter((id) => ownDeviceIds.has(id))) {
        await apiClient.revokeRefreshTokenById(refreshTokenId).catch((err) => console.error(err));
      }
      res.redirect(302, '/account');
    });
    ```
    

For the full application, including the session picker template, see the [example repository](https://github.com/FusionAuth/fusionauth-example-device-limit-friendly). For the webhook approach, see the [webhook example repository](https://github.com/FusionAuth/fusionauth-example-device-limit-simple).

Related

[Authentication Manage Application Sessions in FusionAuth With Refresh Tokens Learn how to track and revoke application sessions in FusionAuth by tying each session to a refresh token. sessionsrefresh tokens](https://fusionauth.io/docs/authentication/sessions/centralized-sessions.md)

[Authentication View and Revoke User Sessions Learn how to list a user's sessions and end the sessions from the Admin UI, the API, or automatically. sessionsrefresh tokenswebhooks](https://fusionauth.io/docs/authentication/sessions/revoke-sessions.md)

[Authentication Configure Session and Token Lifetimes Learn how to set how long users stay logged in to FusionAuth and to your applications. sessionsrefresh tokens](https://fusionauth.io/docs/authentication/sessions/configure-session-lifetimes.md)

[Authentication How Logout Works in FusionAuth Learn about what each FusionAuth logout method ends, and how front-channel logout signs a user out of every application. sessionsrefresh tokens](https://fusionauth.io/docs/authentication/sessions/how-logout-works.md)
---

## Other pages in Sessions

> For the full index of this section, see [Authentication](https://fusionauth.io/docs/llms-authentication.txt).

- [Manage Application Sessions in FusionAuth With Refresh Tokens](https://fusionauth.io/docs/authentication/sessions/centralized-sessions.md): Learn how to track and revoke application sessions in FusionAuth by tying each session to a refresh token.
- [Configure Session and Token Lifetimes](https://fusionauth.io/docs/authentication/sessions/configure-session-lifetimes.md): Learn how to set how long users stay logged in to FusionAuth and to your applications.
- [Login Page Cookies](https://fusionauth.io/docs/authentication/sessions/cookies.md): Reference for the cookies that FusionAuth sets in the browser, including the SSO session cookie.
- [Enable SSO Across Applications](https://fusionauth.io/docs/authentication/sessions/enable-sso.md): Learn how to let users log in once and reach every application in a FusionAuth tenant without logging in again.
- [How Logout Works in FusionAuth](https://fusionauth.io/docs/authentication/sessions/how-logout-works.md): Learn about what each FusionAuth logout method ends, and how front-channel logout signs a user out of every application.
- [How Sessions Work in FusionAuth](https://fusionauth.io/docs/authentication/sessions/how-sessions-work.md): Learn about the sessions that keep a user logged in to FusionAuth and to your applications, and how the sessions relate.
- [Sessions, SSO, and Logout](https://fusionauth.io/docs/authentication/sessions.md): Learn about how FusionAuth keeps users logged in across applications, and how to configure session lifetimes, single sign-on, and logout.
- [Log Users Out of FusionAuth and Your Applications](https://fusionauth.io/docs/authentication/sessions/log-users-out.md): Learn how to log users out of one application or every application, and where to send users after logout.
- [View and Revoke User Sessions](https://fusionauth.io/docs/authentication/sessions/revoke-sessions.md): Learn how to list a user's sessions and end the sessions from the Admin UI, the API, or automatically.
- [Session and Token Lifetime Settings](https://fusionauth.io/docs/authentication/sessions/session-settings.md): Reference for every FusionAuth setting that controls session, token, and logout behavior.
- [Troubleshoot Sessions and Logout](https://fusionauth.io/docs/authentication/sessions/troubleshooting.md): Learn how to fix common problems with FusionAuth SSO, session lifetimes, and logout.
