Skip to content

Quickstart

Hosted auth pages, managed sessions, secure logout. Purpose built. Simple where it counts

You’ll implement sign-up, login, and logout flows with secure session management and user management included. The foundation you build here extends to features like workspaces, enterprise SSO, MCP authentication, and SCIM provisioning.

See the integration in action Play
Review the authentication sequence

Scalekit handles the complex authentication flow while you focus on your core product:

Full-Stack Authentication Flow

  1. User initiates sign-in - Your app redirects to Scalekit’s hosted auth page
  2. Identity verification - User authenticates via their preferred method
  3. Secure callback - Scalekit returns user profile and session tokens
  4. Session creation - Your app establishes a secure user session
  5. Protected access - User accesses your application’s features

Get moving, instantly, with your go-to AI assistant

Input this prompt in your IDE to analyze your existing code base and generate complete auth implementation code accordingly.

*Compatible with Cursor, Windsurf, VS Code, and any AI-powered tools

Copy llm prompt

  1. Use the following instructions to install the SDK for your technology stack.

    npm install @scalekit-sdk/node

  2. Create an authorization URL to redirect users to Scalekit’s sign-in page. Use the Scalekit SDK to construct this URL with your redirect URI and required scopes.

    Express.js
    // Must match the callback URL you registered in step 1
    const redirectUri = 'http://localhost:3000/auth/callback';
    // Request user profile data (openid, profile, email) and session tracking (offline_access)
    // offline_access enables refresh tokens so users can stay logged in across sessions
    const options = {
    scopes: ['openid', 'profile', 'email', 'offline_access']
    };
    const authorizationUrl = scalekit.getAuthorizationUrl(redirectUri, options);
    // Generated URL will look like:
    // https://<SCALEKIT_ENVIRONMENT_URL>/oauth/authorize?response_type=code&client_id=skc_1234&scope=openid%20profile%20email%20offline_access&redirect_uri=https%3A%2F%2Fyourapp.com%2Fauth%2Fcallback
    res.redirect(authorizationUrl);

    This redirects users to Scalekit’s managed sign-in page where they can authenticate. The page includes default authentication methods for users to toggle between sign in and sign up.

  3. After successful authentication, Scalekit creates a user record and sends the user information to your callback endpoint.

    1. Add a callback endpoint in your application (typically https://your-app.com/auth/callback)
    2. Register it in your Scalekit dashboard > Authentication > Redirect URLS > Allowed Callback URLs

    In authentication flow, Scalekit redirects to your callback URL with an authorization code. Your application exchanges this code for the user’s profile information and session tokens.

    import scalekit from '@/utils/auth.js'
    const redirectUri = '<http://localhost:3000/auth/callback>';
    // Get the authorization code from the scalekit initiated callback
    app.get('/auth/callback', async (req, res) => {
    6 collapsed lines
    const { code, error, error_description } = req.query;
    if (error) {
    return res.status(401).json({ error, error_description });
    }
    try {
    // Exchange the authorization code for user profile and session tokens
    // Returns: user (profile info), idToken (JWT with user claims), accessToken (JWT with roles/permissions), refreshToken
    const authResult = await scalekit.authenticateWithCode(
    code, redirectUri
    );
    8 collapsed lines
    const { user, idToken, accessToken, refreshToken } = authResult;
    // idToken: Decode to access full user profile (sub, oid, email, name)
    // accessToken: Contains roles and permissions for authorization decisions
    // refreshToken: Use to obtain new access tokens when they expire
    // "user" object contains the user's profile information
    // Next step: Create a session and log in the user
    res.redirect('/dashboard/profile');
    } catch (err) {
    console.error('Error exchanging code:', err);
    res.status(500).json({ error: 'Failed to authenticate user' });
    }
    });

    The authResult object contains:

    • user - Common user details with email, name, and verification status
    • idToken - JWT containing verified full user identity claims (includes: sub user ID, oid organization ID, email, name, exp expiration)
    • accessToken - Short-lived token that determines current access context (includes: sub user ID, oid organization ID, roles, permissions, exp expiration)
    • refreshToken - Long-lived token to obtain new access tokens
    {
    user: {
    email: "john.doe@example.com",
    emailVerified: true,
    givenName: "John",
    name: "John Doe",
    id: "usr_74599896446906854"
    },
    idToken: "eyJhbGciO..", // Decode for full user details
    accessToken: "eyJhbGciOi..",
    refreshToken: "rt_8f7d6e5c4b3a2d1e0f9g8h7i6j..",
    expiresIn: 299 // in seconds
    }

    The user details are packaged in the form of JWT tokens. Decode the idToken to access full user profile information (email, name, organization ID) and the accessToken to check user roles and permissions for authorization decisions. See Complete login with code exchange for detailed token claim references and verification instructions.

  4. The access token is a JWT that contains the user’s permissions and roles. It expires in 5 minutes (default) but can be configured. When it expires, use the refresh token to obtain a new access token. The refresh token is long-lived and designed for this purpose.

    The Scalekit SDK provides methods to refresh access tokens automatically. However, you must log the user out when the refresh token itself expires or becomes invalid.

    4 collapsed lines
    import cookieParser from 'cookie-parser';
    // Set cookie parser middleware
    app.use(cookieParser());
    // Store access token in HttpOnly cookie with Path scoping to API routes
    res.cookie('accessToken', authResult.accessToken, {
    maxAge: (authResult.expiresIn - 60) * 1000,
    httpOnly: true,
    secure: true,
    path: '/api',
    sameSite: 'strict'
    });
    // Store refresh token in separate HttpOnly cookie with Path scoped to refresh endpoint
    res.cookie('refreshToken', authResult.refreshToken, {
    httpOnly: true,
    secure: true,
    path: '/auth/refresh',
    sameSite: 'strict'
    });

    This sets browser cookies with the session tokens. Every request to your backend needs to verify the accessToken to ensure the user is authenticated. If expired, use the refreshToken to get a new access token.

    // Middleware to verify and refresh tokens if needed
    const verifyToken = async (req, res, next) => {
    try {
    // Get access token from cookie and decrypt it
    const accessToken = req.cookies.accessToken;
    const decryptedAccessToken = decrypt(accessToken);
    4 collapsed lines
    if (!accessToken) {
    return res.status(401).json({ message: 'No access token provided' });
    }
    // Use Scalekit SDK to validate the token
    const isValid = await scalekit.validateAccessToken(decryptedAccessToken);
    if (!isValid) {
    // Use stored refreshToken to get a new access token
    const {
    user,
    idToken,
    accessToken,
    refreshToken: newRefreshToken,
    } = await scalekit.refreshAccessToken(refreshToken);
    // Store the new refresh token
    // Update the cookie with the new access token
    12 collapsed lines
    }
    next();
    };
    // Example of using the middleware to protect routes
    app.get('/dashboard', verifyToken, (req, res) => {
    // The user object is now available in req.user
    res.json({
    message: 'This is a protected route',
    user: req.user
    });
    });

    Authenticated users can access your dashboard. The app enforces session policies using session tokens. To change session policies, go to Dashboard > Authentication > Session Policy in the Scalekit dashboard.

  5. Session persistence depends on the session policy configured in the Scalekit dashboard. To log out a user, clear local session data and invalidate the user’s session in Scalekit.

    app.get('/logout', (req, res) => {
    // Clear all session data including cookies and local storage
    clearSessionData();
    const logoutUrl = scalekit.getLogoutUrl(
    idTokenHint, // ID token to invalidate
    postLogoutRedirectUri // URL that scalekit redirects after session invalidation
    );
    // Redirect the user to the Scalekit logout endpoint to begin invalidating the session.
    res.redirect(logoutUrl); // This URL can only be used once and expires after logout.
    });

    The logout process completes when Scalekit invalidates the user’s session and redirects them to your registered post-logout URL.

This single integration unlocks multiple authentication methods, including Magic Link & OTP, social sign-ins, enterprise single sign-on (SSO), and robust user management features. As you continue working with Scalekit, you’ll discover even more features that enhance your authentication workflows.