Skip to content

Manage user sessions

User sessions determine how long users stay signed in to your application. After users successfully authenticate, you receive session tokens that manage their access. These tokens control session duration, multi-device access, and cross-product authentication within your company’s ecosystem.

Scalekit provides session management capabilities out of the box. Your application receives an access_token and refresh_token in the authentication response. This guide shows you how to store these tokens securely and refresh them before they expire.

  1. After successful user authentication, your application receives session tokens in the response object.

    Express.js
    const authResult = await scalekit.authenticateWithCode(
    code, redirectUri
    );
    // authResult contains user profile and session tokens
    const { user, accessToken, refreshToken, expiresIn } = authResult;

    Store each token based on its security requirements:

    • Access Token: Store in a secure, HTTP-only cookie to prevent XSS attacks. This token has a short lifespan and provides access to protected resources.
    • Refresh Token: Store in your backend database or secure server-side storage. This long-lived token generates new access tokens.

    Here’s how to set secure cookies:

    Express.js
    import cookieParser from 'cookie-parser';
    // Configure cookie parser middleware
    app.use(cookieParser());
    // After receiving the authResult from scalekit.authenticateWithCode()
    const { accessToken, expiresIn, refreshToken, user } = authResult;
    // Store the refresh token in your database
    await db.saveRefreshToken(user.id, refreshToken);
    // Set the access token as a secure cookie
    res.cookie('accessToken', accessToken, {
    maxAge: (expiresIn - 60) * 1000, // Convert to milliseconds, subtract 60s buffer
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict'
    });

    Configure session settings from your Scalekit dashboard’s Session Configuration to control session lifetimes and security policies.

  2. Create middleware to protect your application routes. This middleware validates the access token on every request to secured endpoints.

    middleware/auth.js
    async function verifyToken(req, res, next) {
    const { accessToken } = req.cookies;
    if (!accessToken) {
    return res.status(401).json({ error: 'Authentication required' });
    }
    try {
    // Validate the token using Scalekit SDK
    const { user } = await scalekit.validateAccessToken(accessToken);
    req.user = user; // Attach user information to the request
    next();
    } catch (error) {
    // Token is expired or invalid - attempt to refresh
    return handleTokenRefresh(req, res, next);
    }
    }
  3. When access tokens expire, use the refresh token to get new ones. This maintains user sessions without requiring re-authentication.

    middleware/auth.js
    async function handleTokenRefresh(req, res, next) {
    // Get the user ID from the expired token or session storage
    const userId = req.session?.userId || req.user?.id;
    if (!userId) {
    return res.status(401).json({ error: 'Authentication required' });
    }
    // Retrieve the stored refresh token from your database
    const storedRefreshToken = await db.getRefreshToken(userId);
    if (!storedRefreshToken) {
    return res.status(401).json({ error: 'Session expired' });
    }
    try {
    // Get new tokens using the refresh token
    const authResult = await scalekit.refreshToken(storedRefreshToken);
    const { accessToken, expiresIn, refreshToken: newRefreshToken } = authResult;
    // Update the stored refresh token
    await db.saveRefreshToken(userId, newRefreshToken);
    // Set the new access token as a cookie
    res.cookie('accessToken', accessToken, {
    maxAge: (expiresIn - 60) * 1000,
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict'
    });
    // Attach user information and continue
    req.user = authResult.user;
    next();
    } catch (error) {
    // Refresh failed - user must sign in again
    res.clearCookie('accessToken');
    return res.status(401).json({ error: 'Session expired. Please sign in again.' });
    }
    }

    Apply this middleware to protected routes:

    app.js
    // Protect routes that require authentication
    app.get('/dashboard', verifyToken, (req, res) => {
    res.json({ message: `Welcome ${req.user.name}!` });
    });
    app.get('/api/profile', verifyToken, (req, res) => {
    res.json({ user: req.user });
    });

Control user session behavior from your Scalekit dashboard without changing your application code.

Session Settings Dashboard

You can control how long users stay signed in and how often they need to log in again. In your Scalekit dashboard, the Session settings page lets you set these options:

  • Absolute session timeout: This is the maximum time a user can stay signed in, no matter what. After this time, they must log in again. For example, if you set it to 30 minutes, users will be logged out after 30 minutes, even if they are still using your app.

  • Idle session timeout: This is the time your app waits before logging out a user who is not active. If you turn this on, the session will end if the user does nothing for the set time. For example, if you set it to 10 minutes, and the user does not click or type for 10 minutes, they will be logged out.

  • Access token lifetime: This is how long an access token is valid. When it expires, your app needs to get a new token (using the refresh token) so the user can keep using the app without logging in again. For example, if you set it to 5 minutes, your app will need to refresh the token every 5 minutes.

Shorter timeouts provide better security, while longer timeouts reduce authentication interruptions.