Skip to content

Implement logout

Terminate user sessions across your application and Scalekit

When implementing logout functionality, you need to consider three session layers where user authentication state is maintained:

  1. Application session layer: Your application stores session tokens (access tokens, refresh tokens, ID tokens) in browser cookies. You control this layer completely.

  2. Scalekit session layer: Scalekit maintains a session for the user and stores their information. When users return to Scalekit’s authentication page, their information is remembered for a smoother experience.

  3. Identity provider session layer: When users authenticate with external providers (for example, Okta through enterprise SSO), those providers maintain their own sessions. Users won’t be prompted to sign in again if they’re already signed into the provider.

This guide shows you how to clear the application session layer and invalidate the Scalekit session layer in a single logout endpoint.

  1. Create a /logout endpoint in your application that handles the complete logout flow: extracting the ID token, generating the Scalekit logout URL, clearing session cookies, and redirecting to Scalekit.

    Express.js
    app.get('/logout', (req, res) => {
    // Step 1: Extract the ID token (needed for Scalekit logout)
    const idTokenHint = req.cookies.idToken;
    const postLogoutRedirectUri = 'http://localhost:3000/login';
    // Step 2: Generate the Scalekit logout URL
    const logoutUrl = scalekit.getLogoutUrl(
    idTokenHint, // ID token to invalidate
    postLogoutRedirectUri // URL that scalekit redirects after session invalidation
    );
    // Step 3: Clear all session cookies
    res.clearCookie('accessToken');
    res.clearCookie('refreshToken');
    res.clearCookie('idToken'); // Clear AFTER using it for logout URL
    // Step 4: Redirect to Scalekit to invalidate the session
    res.redirect(logoutUrl);
    });

    Important: The logout flow clears cookies AFTER extracting the ID token and generating the logout URL. This ensures the ID token is available for Scalekit’s logout endpoint.

  2. After users log out, Scalekit redirects them to the URL you specify in the post_logout_redirect_uri parameter. This URL must be registered in your Scalekit dashboard under Dashboard > Authentication > Redirects > Post Logout URL.

    Scalekit only redirects to URLs from your allow list. This prevents unauthorized redirects and protects your users. If you need different redirect URLs for different applications, you can register multiple post-logout URLs in your dashboard.