> **Building with AI coding agents?** If you're using an AI coding agent, install the official Scalekit plugin. It gives your agent full awareness of the Scalekit API — reducing hallucinations and enabling faster, more accurate code generation.
>
> - **Claude Code**: `/plugin marketplace add scalekit-inc/claude-code-authstack` then `/plugin install <auth-type>@scalekit-auth-stack`
> - **GitHub Copilot CLI**: `copilot plugin marketplace add scalekit-inc/github-copilot-authstack` then `copilot plugin install <auth-type>@scalekit-auth-stack`
> - **Codex**: run the bash installer, restart, then open Plugin Directory and enable `<auth-type>`
> - **Skills CLI** (Windsurf, Cline, 40+ agents): `npx skills add scalekit-inc/skills --list` then `--skill <skill-name>`
>
> `<auth-type>` / `<skill-name>`: `agent-auth`, `full-stack-auth`, `mcp-auth`, `modular-sso`, `modular-scim` — [Full setup guide](https://docs.scalekit.com/dev-kit/build-with-ai/)

---

# Pre-check SSO by domain

When using discovery through `loginHint`, validate that the user's email domain has an active SSO connection before redirecting. This prevents dead-end redirects and improves user experience by routing users to the correct authentication path.

## When to use domain pre-checking

Use domain pre-checking when:
- You implement identifier-driven or SSO button flows that collect email first
- You infer SSO availability from the user's email domain
- You want to show helpful error messages for domains without SSO

Skip this check when:
- You already pass `organizationId` explicitly (you know the organization)
- You implement organization-specific pages where SSO is always available

## Implementation workflow

1. ## Capture the user's email and extract the domain

   First, collect the user's email address through your login form.

   ```javascript title="Login form handler"
   // Extract domain from user's email
   const email = req.body.email;
   const domain = email.split('@')[1]; // e.g., "acmecorp.com"
   ```

2. ## Query for SSO connections by domain

   Use the Scalekit API to check if the domain has an active SSO connection configured.

   ```javascript title="Express.js"
   // Use case: Check if user's domain has SSO before redirecting
   app.post('/auth/check-sso', async (req, res) => {
     const { email } = req.body;
     const domain = email.split('@')[1];

     try {
       // Query Scalekit for connections matching this domain
       const connections = await scalekit.connection.listConnections({
         domain: domain
       });

       if (connections.length > 0) {
         // Domain has active SSO - redirect to SSO login
         const authorizationURL = scalekit.getAuthorizationUrl(
           process.env.REDIRECT_URI,
           { loginHint: email }
         );
         res.json({ ssoAvailable: true, redirectUrl: authorizationURL });
       } else {
         // No SSO configured - route to password or social login
         res.json({ ssoAvailable: false, message: 'Please use password login' });
       }
     } catch (error) {
       console.error('Failed to check SSO availability:', error);
       res.status(500).json({ error: 'sso_check_failed' });
     }
   });
   ```

   ```python title="Flask"
   # Use case: Check if user's domain has SSO before redirecting
   @app.route('/auth/check-sso', methods=['POST'])
   def check_sso():
       data = request.get_json()
       email = data.get('email')
       domain = email.split('@')[1]

       try:
           # Query Scalekit for connections matching this domain
           connections = scalekit_client.connection.list_connections(
               domain=domain
           )

           if len(connections) > 0:
               # Domain has active SSO - redirect to SSO login
               authorization_url = scalekit_client.get_authorization_url(
                   redirect_uri=os.getenv("REDIRECT_URI"),
                   options=AuthorizationUrlOptions(login_hint=email)
               )
               return jsonify({
                   'ssoAvailable': True,
                   'redirectUrl': authorization_url
               })
           else:
               # No SSO configured - route to password or social login
               return jsonify({
                   'ssoAvailable': False,
                   'message': 'Please use password login'
               })
       except Exception as error:
           print(f"Failed to check SSO availability: {error}")
           return jsonify({'error': 'sso_check_failed'}), 500
   ```

   ```go title="Gin"
   // Use case: Check if user's domain has SSO before redirecting
   func checkSSOHandler(c *gin.Context) {
       var body struct {
           Email string `json:"email"`
       }
       c.BindJSON(&body)

       domain := strings.Split(body.Email, "@")[1]

       // Query Scalekit for connections matching this domain
       connections, err := scalekitClient.Connection.ListConnections(
           &scalekit.ListConnectionsOptions{
               Domain: domain,
           },
       )

       if err != nil {
           log.Printf("Failed to check SSO availability: %v", err)
           c.JSON(http.StatusInternalServerError, gin.H{"error": "sso_check_failed"})
           return
       }

       if len(connections) > 0 {
           // Domain has active SSO - redirect to SSO login
           authorizationURL, _ := scalekitClient.GetAuthorizationUrl(
               os.Getenv("REDIRECT_URI"),
               scalekit.AuthorizationUrlOptions{
                   LoginHint: body.Email,
               },
           )
           c.JSON(http.StatusOK, gin.H{
               "ssoAvailable": true,
               "redirectUrl":  authorizationURL,
           })
       } else {
           // No SSO configured - route to password or social login
           c.JSON(http.StatusOK, gin.H{
               "ssoAvailable": false,
               "message":      "Please use password login",
           })
       }
   }
   ```

   ```java title="Spring Boot"
   // Use case: Check if user's domain has SSO before redirecting
   @PostMapping(path = "/auth/check-sso")
   public ResponseEntity<Map<String, Object>> checkSSOHandler(@RequestBody CheckSSORequest body) {
       String email = body.getEmail();
       String domain = email.split("@")[1];

       try {
           // Query Scalekit for connections matching this domain
           ListConnectionsResponse connections = scalekitClient
               .connection()
               .listConnections(
                   new ListConnectionsOptions().setDomain(domain)
               );

           if (!connections.getConnections().isEmpty()) {
               // Domain has active SSO - redirect to SSO login
               String authorizationURL = scalekitClient
                   .authentication()
                   .getAuthorizationUrl(
                       System.getenv("REDIRECT_URI"),
                       new AuthorizationUrlOptions().setLoginHint(email)
                   )
                   .toString();

               Map<String, Object> response = new HashMap<>();
               response.put("ssoAvailable", true);
               response.put("redirectUrl", authorizationURL);
               return ResponseEntity.ok(response);
           } else {
               // No SSO configured - route to password or social login
               Map<String, Object> response = new HashMap<>();
               response.put("ssoAvailable", false);
               response.put("message", "Please use password login");
               return ResponseEntity.ok(response);
           }
       } catch (Exception error) {
           System.err.println("Failed to check SSO availability: " + error.getMessage());
           return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
               .body(Collections.singletonMap("error", "sso_check_failed"));
       }
   }
   ```

3. ## Route users based on SSO availability

   Based on the API response, either redirect to SSO or show alternative authentication options.

   ```javascript title="Client-side routing"
   // Handle the response from your backend
   const response = await fetch('/auth/check-sso', {
     method: 'POST',
     headers: { 'Content-Type': 'application/json' },
     body: JSON.stringify({ email: userEmail })
   });

   const data = await response.json();

   if (data.ssoAvailable) {
     // Redirect to SSO login
     window.location.href = data.redirectUrl;
   } else {
     // Show password login or social authentication options
     showPasswordLoginForm();
   }
   ```
**Note:** This API returns results only when organizations have configured their domains in Scalekit through **Dashboard > Organizations > [Organization] > Domains**. See the <a href="https://docs.scalekit.com/apis/#tag/connections/get/api/v1/connections" target="_blank" rel="noopener">connections API reference</a> for complete details.

---

## More Scalekit documentation

| Resource | What it contains | When to use it |
|----------|-----------------|----------------|
| [/llms.txt](/llms.txt) | Structured index with routing hints per product area | Start here — find which documentation set covers your topic before loading full content |
| [/llms-full.txt](/llms-full.txt) | Complete documentation for all Scalekit products in one file | Use when you need exhaustive context across multiple products or when the topic spans several areas |
| [sitemap-0.xml](https://docs.scalekit.com/sitemap-0.xml) | Full URL list of every documentation page | Use to discover specific page URLs you can fetch for targeted, page-level answers |
