Skip to main content
Scalekit provides complete authentication infrastructure for modern applications. This quickstart guides you through implementing user authentication with hosted auth pages, managed sessions, and secure logout.

What you’ll build

You’ll implement:
  • Sign-up and login flows with hosted authentication pages
  • Secure session management with token validation and refresh
  • Logout functionality with session invalidation
  • Foundation for enterprise SSO, workspaces, and user management

Prerequisites

Before you begin:
  • Create a Scalekit account at app.scalekit.com
  • Get your API credentials from Dashboard > Developers > Settings > API Credentials
  • Have a development environment with Node.js, Python, Go, or Java

Implementation steps

1
Install Scalekit SDK
2
Install the SDK for your technology stack:
3
Node.js
npm install @scalekit-sdk/node
Python
pip install scalekit-sdk-python
Go
go get github.com/scalekit-inc/scalekit-sdk-go
Java
mvn dependency:get -Dartifact=com.scalekit:scalekit-sdk-java:1.0.0
4
Add your Scalekit credentials to your environment variables:
5
SCALEKIT_ENVIRONMENT_URL=<your-environment-url>
SCALEKIT_CLIENT_ID=<your-client-id>
SCALEKIT_CLIENT_SECRET=<your-client-secret>
6
Redirect users to sign up or login
7
Create an authorization URL to redirect users to Scalekit’s hosted authentication page:
8
Node.js
import { Scalekit } from '@scalekit-sdk/node';

const scalekit = new Scalekit(
  process.env.SCALEKIT_ENVIRONMENT_URL,
  process.env.SCALEKIT_CLIENT_ID,
  process.env.SCALEKIT_CLIENT_SECRET
);

// Must match the allowed callback URL in your dashboard
const redirectUri = 'http://localhost:3000/auth/callback';

const options = {
  scopes: ['openid', 'profile', 'email', 'offline_access']
};

const authorizationUrl = scalekit.getAuthorizationUrl(redirectUri, options);
res.redirect(authorizationUrl);
Python
from scalekit import ScalekitClient, AuthorizationUrlOptions

scalekit_client = ScalekitClient(
    os.getenv('SCALEKIT_ENVIRONMENT_URL'),
    os.getenv('SCALEKIT_CLIENT_ID'),
    os.getenv('SCALEKIT_CLIENT_SECRET')
)

redirect_uri = 'http://localhost:3000/auth/callback'

options = AuthorizationUrlOptions(
    scopes=['openid', 'profile', 'email', 'offline_access']
)

authorization_url = scalekit_client.get_authorization_url(redirect_uri, options)
return redirect(authorization_url)
Go
import "github.com/scalekit-inc/scalekit-sdk-go"

scalekitClient := scalekit.NewScalekitClient(
    os.Getenv("SCALEKIT_ENVIRONMENT_URL"),
    os.Getenv("SCALEKIT_CLIENT_ID"),
    os.Getenv("SCALEKIT_CLIENT_SECRET"),
)

redirectUri := "http://localhost:3000/auth/callback"

options := scalekit.AuthorizationUrlOptions{
    Scopes: []string{"openid", "profile", "email", "offline_access"},
}

authorizationUrl, err := scalekitClient.GetAuthorizationUrl(redirectUri, options)
if err != nil {
    panic(err)
}

c.Redirect(http.StatusFound, authorizationUrl.String())
Java
import com.scalekit.ScalekitClient;
import com.scalekit.internal.http.AuthorizationUrlOptions;

ScalekitClient scalekitClient = new ScalekitClient(
    System.getenv("SCALEKIT_ENVIRONMENT_URL"),
    System.getenv("SCALEKIT_CLIENT_ID"),
    System.getenv("SCALEKIT_CLIENT_SECRET")
);

String redirectUri = "http://localhost:3000/auth/callback";

AuthorizationUrlOptions options = new AuthorizationUrlOptions();
options.setScopes(Arrays.asList("openid", "profile", "email", "offline_access"));

URL authorizationUrl = scalekitClient.authentication().getAuthorizationUrl(redirectUri, options);
9
Register your redirect URLs in Dashboard > Authentication > Redirect URLs before implementing the callback.
10
Handle the authentication callback
11
After successful authentication, Scalekit redirects to your callback URL with an authorization code. Exchange this code for user details and session tokens:
12
Node.js
app.get('/auth/callback', async (req, res) => {
  const { code, error, error_description } = req.query;

  if (error) {
    return res.status(401).json({ error, error_description });
  }

  try {
    const authResult = await scalekit.authenticateWithCode(
      code,
      redirectUri
    );

    const { user, idToken, accessToken, refreshToken } = authResult;
    
    // Store tokens securely and create session
    res.redirect('/dashboard/profile');
  } catch (err) {
    console.error('Authentication failed:', err);
    res.status(500).json({ error: 'Failed to authenticate user' });
  }
});
Python
@app.route('/auth/callback')
def callback():
    code = request.args.get('code')
    error = request.args.get('error')
    
    if error:
        return jsonify({'error': error}), 401
    
    try:
        auth_result = scalekit_client.authenticate_with_code(
            code,
            redirect_uri
        )
        
        user = auth_result.user
        # Store tokens securely and create session
        return redirect('/dashboard/profile')
    except Exception as err:
        return jsonify({'error': 'Authentication failed'}), 500
Go
func callbackHandler(c *gin.Context) {
    code := c.Query("code")
    errorParam := c.Query("error")
    
    if errorParam != "" {
        c.JSON(http.StatusUnauthorized, gin.H{"error": errorParam})
        return
    }
    
    options := scalekit.AuthenticationOptions{}
    authResult, err := scalekitClient.AuthenticateWithCode(
        c.Request.Context(), code, redirectUri, options,
    )
    
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Authentication failed"})
        return
    }
    
    user := authResult.User
    // Store tokens securely and create session
    c.Redirect(http.StatusFound, "/dashboard/profile")
}
Java
@GetMapping("/auth/callback")
public Object callback(
    @RequestParam(required = false) String code,
    @RequestParam(required = false) String error
) {
    if (error != null) {
        // Handle error
    }
    
    try {
        AuthenticationOptions options = new AuthenticationOptions();
        AuthenticationResponse authResult = scalekitClient
            .authentication()
            .authenticateWithCode(code, redirectUri, options);
        
        var user = authResult.getIdTokenClaims();
        // Store tokens securely and create session
        return new RedirectView("/dashboard/profile");
    } catch (Exception err) {
        // Handle exception
    }
}
13
Create and manage user sessions
14
Store session tokens securely using HttpOnly cookies:
15
Node.js
res.cookie('accessToken', authResult.accessToken, {
  maxAge: (authResult.expiresIn - 60) * 1000,
  httpOnly: true,
  secure: true,
  sameSite: 'strict'
});

res.cookie('refreshToken', authResult.refreshToken, {
  httpOnly: true,
  secure: true,
  path: '/auth/refresh',
  sameSite: 'strict'
});
Python
response.set_cookie(
    'accessToken',
    auth_result.access_token,
    max_age=auth_result.expires_in - 60,
    httponly=True,
    secure=True,
    samesite='Strict'
)

response.set_cookie(
    'refreshToken',
    auth_result.refresh_token,
    httponly=True,
    secure=True,
    path='/auth/refresh',
    samesite='Strict'
)
Go
c.SetSameSite(http.SameSiteStrictMode)

c.SetCookie(
    "accessToken",
    authResult.AccessToken,
    authResult.ExpiresIn-60,
    "/",
    "",
    true,
    true,
)

c.SetCookie(
    "refreshToken",
    authResult.RefreshToken,
    0,
    "/auth/refresh",
    "",
    true,
    true,
)
Java
Cookie accessTokenCookie = new Cookie("accessToken", authResult.getAccessToken());
accessTokenCookie.setMaxAge(authResult.getExpiresIn() - 60);
accessTokenCookie.setHttpOnly(true);
accessTokenCookie.setSecure(true);
response.addCookie(accessTokenCookie);

Cookie refreshTokenCookie = new Cookie("refreshToken", authResult.getRefreshToken());
refreshTokenCookie.setHttpOnly(true);
refreshTokenCookie.setSecure(true);
refreshTokenCookie.setPath("/auth/refresh");
response.addCookie(refreshTokenCookie);
16
Log out the user
17
Clear session data and invalidate the user’s session:
18
Node.js
app.get('/logout', (req, res) => {
  clearSessionData();
  
  const logoutUrl = scalekit.getLogoutUrl(
    idTokenHint,
    postLogoutRedirectUri
  );
  
  res.redirect(logoutUrl);
});
Python
@app.route('/logout')
def logout():
    clear_session_data()
    
    options = LogoutUrlOptions(
        id_token_hint=id_token,
        post_logout_redirect_uri=post_logout_redirect_uri
    )
    logout_url = scalekit_client.get_logout_url(options)
    
    return redirect(logout_url)
Go
func logoutHandler(c *gin.Context) {
    clearSessionData()
    
    options := scalekit.LogoutUrlOptions{
        IdTokenHint: idToken,
        PostLogoutRedirectUri: postLogoutRedirectUri,
    }
    logoutUrl, _ := scalekitClient.GetLogoutUrl(options)
    
    c.Redirect(http.StatusFound, logoutUrl.String())
}
Java
@GetMapping("/logout")
public RedirectView logout() {
    clearSessionData();
    
    LogoutUrlOptions options = new LogoutUrlOptions();
    options.setIdTokenHint(idToken);
    options.setPostLogoutRedirectUri(postLogoutRedirectUri);
    
    URL logoutUrl = scalekitClient.authentication().getLogoutUrl(options);
    return new RedirectView(logoutUrl.toString());
}

Next steps

Core Concepts

Understand authentication flows and session management

Enterprise SSO

Add enterprise SSO for your customers

API Reference

Explore the complete API documentation

SDKs

Learn more about SDK features and configuration

Build docs developers (and LLMs) love