Skip to content

Quickstart

Get up and running with Scalekit’s Full Stack Authentication in under 10 minutes. You’ll build a complete authentication flow with hosted sign-in pages, user session management, and secure logout - all optimized for B2B SaaS applications.

By the end of this guide, your application will have:

  • Hosted authentication pages - Let Scalekit handle sign-in/sign-up UI
  • Multi-tenant user management - Automatic workspace separation for B2B apps
  • Session management - Secure token handling with automatic refresh
  • Multiple auth methods - Email/password, social logins, and enterprise SSO
  • Secure logout - Complete session invalidation

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 can access your application’s features
  • Signup for a Scalekit account
  • Copy your API credentials from the Scalekit dashboard’s API Config section
  • Register your redirect URLs in the Scalekit Dashboard under Redirects section

Let’s get started!

  1. npm install @scalekit-sdk/node

    Copy your API credentials from the Scalekit dashboard’s API Config section and set them as environment variables.

    Terminal window
    SCALEKIT_ENVIRONMENT_URL='<YOUR_ENVIRONMENT_URL>'
    SCALEKIT_CLIENT_ID='<ENVIRONMENT_CLIENT_ID>'
    SCALEKIT_CLIENT_SECRET='<ENVIRONMENT_CLIENT_SECRET>'

    Create a new Scalekit client instance after initializing the environment variables.

    utils/auth.js
    import { Scalekit } from '@scalekit-sdk/node';
    export let scalekit = new Scalekit(
    process.env.SCALEKIT_ENVIRONMENT_URL,
    process.env.SCALEKIT_CLIENT_ID,
    process.env.SCALEKIT_CLIENT_SECRET
    );
  2. Generate the authorization URL by passing a registered callback URL and scopes to the Scalekit SDK.

    Express.js
    const redirectUri = '<http://localhost:3000/api/callback>';
    const options = {
    scopes: ['openid', 'profile', 'email', 'offline_access']
    };
    const authorizationUrl = scalekit.getAuthorizationUrl(redirectUri, options);
    res.redirect(authorizationUrl);

    This will redirect the user to Scalekit’s managed sign-in page.

  3. After users authenticate, Scalekit redirects them back to your registered callback URL with an authorization code. Exchange this code to get the user’s profile and session tokens:

    import scalekit from '@/utils/auth.js'
    const redirectUri = '<http://localhost:3000/api/callback>';
    // Get the authorization code from the scalekit initiated callback
    app.get('/api/callback', async (req, res) => {
    const { code, error, error_description } = req.query;
    if (error) {
    return res.status(401).json({ error, error_description });
    }
    try {
    // Exchange the authorization code for a user profile
    const authResult = await scalekit.authenticateWithCode(
    code, redirectUri
    );
    const { user } = authResult;
    // "user" object contains the user's profile information
    // Next step: Create a session and log in the user
    5 collapsed lines
    res.redirect('/dashboard/profile');
    } catch (err) {
    console.error('Error exchanging code:', err);
    res.status(500).json({ error: 'Failed to authenticate user' });
    }
    });

    The authenticateWithCode method returns an object containing the user’s profile information (user object) and session tokens including idToken, accessToken and refreshToken.

    {
    user: {
    email: "john.doe@example.com",
    emailVerified: true,
    givenName: "John",
    name: "John Doe",
    id: "usr_74599896446906854"
    },
    idToken: "eyJhbGciO..",
    accessToken: "eyJhbGciOi..",
    refreshToken: "rt_8f7d6e5c4b3a2d1e0f9g8h7i6j..",
    expiresIn: 299
    }

    You can decode the idToken to access user information like email, name, and profile verification status directly from the token claims.

  4. Now that you’ve the entire user’s profile details including their email address, verification status, create a secure session by storing the session tokens. Use encrypted HTTP-only cookies for the access token and securely store the refresh token:

    import cookieParser from 'cookie-parser';
    // Set cookie parser middleware
    app.use(cookieParser());
    // encrypt the accessToken using a secure encryption algorithm
    const encryptedAccessToken = encrypt(authResult.accessToken);
    // setting up accessToken as HTTP-only cookie
    res.cookie('accessToken', encryptedAccessToken, {
    maxAge: (authResult.expiresIn - 60) * 1000,
    httpOnly: true,
    secure: true,
    path: '/',
    sameSite: 'strict'
    });
    // Store the refreshToken in a secure place

    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
    const accessToken = req.cookies.accessToken;
    // Decrypt the accessToken using the same encryption algorithm
    const decryptedAccessToken = decrypt(accessToken);
    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.refreshToken(refreshToken);
    // Store the new refresh token
    // Update the cookie with the new access token
    }
    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
    });
    });

    Successfully authenticated users can now access your dashboard.

  5. To properly log out users, clear local session data and invalidate their session on Scalekit’s servers:

    /**
    * Handles user logout by:
    * 1. Clearing local session data
    * 2. Invalidating the Scalekit session
    * 3. Redirecting to post-logout URL
    */
    app.get('/logout', (req, res) => {
    // Clear all session data including cookies and local storage
    clearSessionData();
    /**
    * Generates a Scalekit logout URL that will:
    * - Invalidate the user's session on Scalekit's servers
    * - Redirect the user to the specified post-logout URL
    * @param {string} idToken - The user's ID token to invalidate
    * @param {string} postLogoutRedirectUri - URL to redirect after logout
    * @returns {string} The complete logout URL
    */
    const logoutUrl = scalekit.getLogoutUrl(
    idToken,
    postLogoutRedirectUri
    );
    // Redirect to Scalekit's logout endpoint
    // Note: This is a one-time use URL that becomes invalid after use
    res.redirect(logoutUrl);
    });

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

🎉 Congratulations! You’ve successfully integrated Scalekit’s Full Stack Authentication. Your application now has:

  • Complete authentication flow - Sign-in, sign-up, and logout
  • Secure session management - Encrypted tokens with automatic refresh
  • Multi-tenant architecture - Ready for B2B SaaS scaling
  • Enterprise-ready foundation - Built to handle SSO and advanced auth methods

You’ve completed the Scalekit quickstart and enabled secure authentication for your users and sign-in flow.