DEV Community

Saif for Scalekit Inc

Posted on

Add Enterprise SSO to Your Next.js App in Minutes Using Claude Code & Scalekit

The old way: Spend hours reading OAuth documentation, configuring SAML endpoints, building login flows, handling token validation, and creating admin portals for your enterprise customers.

The new way: Describe what you want in plain English. Let Claude Code and Scalekit's plugin do the rest.

This guide shows you how to add production-ready enterprise Single Sign-On to a Next.js application using Claude Code's plugin ecosystem—going from zero to a working SSO flow with customer self-service portal in under 10 minutes.


Table of Contents


What You're Building

By the end of this guide, you'll have:

1. Enterprise SSO Authentication Flow

  • Users enter their work email (user@company.com)
  • Automatic redirect to their organization's identity provider (Microsoft Entra ID, Okta, Google Workspace, etc.)
  • Secure callback handling with token validation
  • Session creation with verified user identity

2. Self-Service Admin Portal

  • Your B2B customers configure their own IDP connections
  • No engineering involvement needed for enterprise onboarding
  • Support for SAML and OIDC protocols
  • Real-time connection status monitoring

3. Production-Ready Code

  • Environment-based configuration
  • Proper error handling
  • Security best practices baked in
  • Next.js App Router patterns

Understanding the Plugin Architecture

Before we dive in, let's understand what makes this possible.

What Are Claude Code Plugins?

Claude Code plugins are packaged bundles of capabilities that extend what Claude can do. Think of them as specialized skill packs that teach Claude how to work with specific services, frameworks, or patterns.

A plugin can contain:

  • Skills: Context-aware instruction sets Claude automatically uses when relevant
  • MCP Servers: Connections to external APIs and services via Model Context Protocol
  • Commands: Slash commands you invoke manually (e.g., /deploy)
  • Subagents: Specialized AI agents for specific tasks (e.g., security review)
  • Hooks: Scripts that run on specific events (pre-commit, post-deployment)

How Scalekit's Plugin Works

The Scalekit Auth Stack plugin gives Claude Code:

  1. Documentation Access: Real-time access to Scalekit's implementation guides via MCP
  2. API Integration: Ability to query your Scalekit environment, retrieve config, manage connections
  3. Implementation Patterns: Battle-tested code patterns for SSO flows, session management, and security
  4. Framework Knowledge: How to properly integrate with Next.js, Express, FastAPI, and other frameworks

When you ask Claude to "add SSO," it:

  • Reads your existing codebase structure
  • Pulls relevant Scalekit documentation
  • Queries your Scalekit environment via MCP
  • Generates complete, working code that follows your project's patterns

Prerequisites

Required:

You'll need from Scalekit:

  • Environment URL (e.g., https://yourenv.scalekit.com)
  • Client ID (from your Scalekit dashboard)
  • Client Secret (generate in dashboard, keep secure)

Time investment: ~10 minutes


Step-by-Step Implementation

Step 1: Install the Scalekit Plugin

Open your terminal and start the Claude Code REPL:

claude
Enter fullscreen mode Exit fullscreen mode

Add the Scalekit Auth Stack marketplace:

/plugin marketplace add scalekit-inc/claude-code-authstack
Enter fullscreen mode Exit fullscreen mode

You should see confirmation:

❯ /plugin marketplace add scalekit-inc/claude-code-authstack

⎿  Successfully added marketplace: scalekit-auth-stack
Enter fullscreen mode Exit fullscreen mode

Now install the Modular SSO plugin:

/plugin install modular-sso@scalekit-auth-stack
Enter fullscreen mode Exit fullscreen mode

What just happened?

  • Claude Code now has access to Scalekit's SSO implementation knowledge
  • The plugin includes MCP servers that can query your Scalekit environment
  • Skills are loaded that guide code generation for auth flows

Verify installation:

/plugins
Enter fullscreen mode Exit fullscreen mode

You should see modular-sso in your installed plugins list.

Step 2: Navigate to Your Project

Exit the REPL (Ctrl+D or exit) and navigate to your Next.js project:

cd /path/to/your-nextjs-app
Enter fullscreen mode Exit fullscreen mode

Start Claude Code in your project:

claude
Enter fullscreen mode Exit fullscreen mode

Step 3: Give Claude the Objective

Here's where the magic happens. Paste this prompt:

My goal is to add SSO to my application and also let my customers 
configure SSO connections with their IDP using an admin portal.
Enter fullscreen mode Exit fullscreen mode

Watch Claude work:

  1. Skill Detection: Claude automatically identifies the Modular SSO skill is relevant
  2. Codebase Analysis: Reads your package.json, route structure, and existing patterns
  3. Documentation Retrieval: Fetches Scalekit's implementation guide via MCP
  4. Environment Discovery: Queries your Scalekit account to get environment details
  5. Code Generation: Creates all necessary files following Next.js conventions

You'll see output like:

Loading skill: Modular SSO
Analyzing project structure...
Reading Next.js configuration...
Fetching Scalekit environment configuration...
Found environment: https://yourenv.scalekit.com
Retrieved Client ID: sk_live_...
Enter fullscreen mode Exit fullscreen mode

Step 4: Approve the Redirect URI

Claude will ask permission to configure a redirect URI in your Scalekit environment:

I need to add a redirect URI to your Scalekit environment:
http://localhost:3000/api/auth/callback

Allow? [y/n]
Enter fullscreen mode Exit fullscreen mode

Type y and press Enter.

Why this matters:
The redirect URI is where Scalekit sends users after they authenticate with their IDP. It must be registered for security—preventing malicious sites from receiving your auth callbacks.

Step 5: Add Your Client Secret

Claude will generate a .env.local file with:

SCALEKIT_ENV_URL=https://yourenv.scalekit.com
SCALEKIT_CLIENT_ID=sk_live_abc123...
SCALEKIT_CLIENT_SECRET=
Enter fullscreen mode Exit fullscreen mode

Open your Scalekit dashboard, navigate to Settings → API Keys, and generate a new Client Secret.

Copy it and add to .env.local:

SCALEKIT_CLIENT_SECRET=sk_secret_xyz789...
Enter fullscreen mode Exit fullscreen mode

Security note: Never commit this file. Claude should have added it to .gitignore automatically.

Step 6: Review Generated Files

Claude will have created:

your-app/
├── .env.local                          # Environment configuration
├── app/
│   ├── api/
│   │   └── auth/
│   │       ├── [org]/
│   │       │   └── route.ts           # SSO initiation
│   │       └── callback/
│   │           └── route.ts           # OAuth callback handler
│   ├── login/
│   │   └── page.tsx                   # Login page with email input
│   └── sso-settings/
│       └── page.tsx                   # Admin portal for IDP config
├── lib/
│   └── scalekit.ts                    # Scalekit client initialization
└── middleware.ts                       # Session validation (optional)
Enter fullscreen mode Exit fullscreen mode

Key file: lib/scalekit.ts

import { ScalekitClient } from '@scalekit-sdk/node';

export const scalekit = new ScalekitClient(
  process.env.SCALEKIT_ENV_URL!,
  process.env.SCALEKIT_CLIENT_ID!,
  process.env.SCALEKIT_CLIENT_SECRET!
);
Enter fullscreen mode Exit fullscreen mode

Key file: app/api/auth/callback/route.ts

import { scalekit } from '@/lib/scalekit';
import { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const code = searchParams.get('code');
  const error = searchParams.get('error');

  if (error) {
    return Response.redirect('/login?error=' + error);
  }

  if (!code) {
    return Response.redirect('/login?error=no_code');
  }

  try {
    // Exchange code for user identity
    const result = await scalekit.authenticateWithCode(
      code,
      request.nextUrl.origin + '/api/auth/callback'
    );

    // Create session with user data
    // (Implementation depends on your session strategy)

    return Response.redirect('/dashboard');
  } catch (err) {
    console.error('Auth error:', err);
    return Response.redirect('/login?error=auth_failed');
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Install Dependencies

Claude should have updated package.json, but verify:

pnpm install
# or npm install, or yarn install
Enter fullscreen mode Exit fullscreen mode

Testing with the IDP Simulator

You don't need a real enterprise IDP to test this. Scalekit provides a built-in simulator.

Start Your Dev Server

pnpm dev
Enter fullscreen mode Exit fullscreen mode

Navigate to http://localhost:3000—you should be redirected to /login.

Use the Test Organization

In your Scalekit dashboard:

  1. Go to Organizations
  2. Find the Test Organization (created by default)
  3. Note it's configured with example.com as an organization domain
  4. The IDP is set to IDP Simulator (simulates Okta/Microsoft/Google)

Test the Flow

  1. On the login page, enter: yourname@example.com
  2. Click Continue
  3. You'll be redirected to the IDP Simulator (looks like a real enterprise login page)
  4. Enter any name in the form
  5. Click Simulate Login

What happens:

  • Scalekit matches example.com to the Test Organization
  • Redirects to the configured IDP (Simulator)
  • Simulator "authenticates" the user
  • Redirects back to your app at /api/auth/callback?code=...
  • Your app exchanges the code for user identity
  • Session is created, user is logged in

Check the Admin Portal

Navigate to http://localhost:3000/sso-settings

You should see:

  • Connected Identity Providers section
  • Status of each IDP (Enabled/Disabled)
  • Available IDPs to configure (Microsoft Entra ID, Okta, Google, etc.)

This is what your enterprise customers will use to self-serve their SSO configuration.


How It Actually Works

Let's demystify what just happened.

The SSO Flow

1. User visits app
   ↓
2. Redirected to /login
   ↓
3. User enters work email: user@acme.com
   ↓
4. App calls Scalekit: "Get SSO URL for acme.com"
   ↓
5. Scalekit checks: Is there an org with domain acme.com?
   ↓
6. If yes: Return IDP login URL for that org
   ↓
7. User redirected to their company's IDP (Okta/Microsoft/etc)
   ↓
8. User authenticates at IDP
   ↓
9. IDP redirects back to: yourapp.com/api/auth/callback?code=xyz
   ↓
10. App exchanges code with Scalekit for user identity
    ↓
11. Scalekit returns: { email, name, organization, ... }
    ↓
12. App creates session, user is logged in
Enter fullscreen mode Exit fullscreen mode

Organization-Based Routing

The key insight: Scalekit routes authentication based on email domain.

When a user enters jane@acme.com:

  • Scalekit looks up which organization owns acme.com
  • Retrieves that organization's configured IDP
  • Returns the appropriate login URL

This is why your B2B customers can each use different IDPs—routing happens automatically per organization.

The Admin Portal

The self-service portal uses Scalekit's management APIs to:

  1. List Organizations: Show the customer their organization details
  2. Configure Connections: Let them set up SAML/OIDC with their IDP
  3. Test Connections: Validate the setup before going live
  4. Manage Domains: Add/remove email domains for their org

All without your engineering team touching anything.

Security Considerations Built In

The generated code includes:

  • PKCE (Proof Key for Code Exchange): Protects against authorization code interception
  • State Parameter: Prevents CSRF attacks
  • Token Validation: Ensures codes haven't been tampered with
  • Environment-Based Config: Secrets never in version control
  • HTTPS Enforcement: Redirect URIs must use HTTPS in production

Production Considerations

Environment Variables

For production, set these in your hosting platform (Vercel, AWS, etc.):

SCALEKIT_ENV_URL=https://yourenv.scalekit.com
SCALEKIT_CLIENT_ID=sk_live_...
SCALEKIT_CLIENT_SECRET=sk_secret_...
Enter fullscreen mode Exit fullscreen mode

Update Redirect URIs

In your Scalekit dashboard, add production callback URLs:

https://yourdomain.com/api/auth/callback
Enter fullscreen mode Exit fullscreen mode

Session Management

Claude generates a basic session setup. For production, consider:

  • Session Storage: Redis, database, or encrypted cookies
  • Session Lifetime: How long until re-authentication required
  • Token Refresh: For long-lived sessions
  • Multi-Device: Handling concurrent sessions

Error Handling

Add user-friendly error messages:

// app/login/page.tsx
const errorMessages = {
  no_code: 'Authentication failed. Please try again.',
  auth_failed: 'Could not verify your identity.',
  invalid_email: 'Please use your work email address.',
  no_org: 'Your organization has not set up SSO yet.'
};
Enter fullscreen mode Exit fullscreen mode

Monitoring

Track:

  • Failed authentication attempts
  • Organization-wise SSO usage
  • IDP connection health
  • Session creation/destruction

Scalekit provides webhooks for these events.


Alternative: Using Other AI Coding Agents

Scalekit's Auth Stack works with 40+ AI coding agents, not just Claude Code.

GitHub Copilot CLI

# Install marketplace
copilot plugin marketplace add scalekit-inc/github-copilot-authstack

# Install plugin
copilot plugin install modular-sso@scalekit-auth-stack

# Generate implementation
copilot "Add Scalekit SSO to my app with admin portal for customer IDP configuration"
Enter fullscreen mode Exit fullscreen mode

Cursor

Option: Use Claude Code marketplace (works now)

# In Claude Code REPL
/plugin marketplace add scalekit-inc/claude-code-authstack

# Cursor automatically picks up Claude Code plugins
# Open Cursor → Settings → Plugins → Enable Modular SSO
Enter fullscreen mode Exit fullscreen mode

Then use Cursor's chat with Cmd+L / Ctrl+L:

Add Scalekit SSO with customer admin portal for IDP configuration
Enter fullscreen mode Exit fullscreen mode

Any Agent via Vercel Skills

# Interactive install
npx skills add scalekit-inc/skills

# Or list and pick
npx skills add scalekit-inc/skills --list

# Install specific skill
npx skills add scalekit-inc/skills --skill modular-sso

# Global install for all projects
npx skills add scalekit-inc/skills --all --global
Enter fullscreen mode Exit fullscreen mode

Supported agents: Windsurf, Cline, Gemini CLI, OpenCode, Codex, and 30+ others.


Why This Matters

Traditional SSO implementation:

  • Read OAuth 2.0 / SAML spec (hours)
  • Study IDP-specific quirks (hours)
  • Write authorization URL generation (30 min)
  • Handle callback and token exchange (1 hour)
  • Build session management (2+ hours)
  • Create admin UI for IDP config (3+ hours)
  • Test with multiple IDPs (hours)
  • Debug edge cases (days)

Total: 1-2 weeks for an experienced developer

With Claude Code + Scalekit:

  • Install plugin (1 minute)
  • Describe what you want (30 seconds)
  • Review generated code (5 minutes)
  • Test with simulator (2 minutes)

Total: ~10 minutes

The code quality is production-ready because:

  1. The plugin encodes battle-tested patterns from thousands of implementations
  2. It follows your framework's conventions automatically
  3. Security best practices are baked in
  4. Scalekit handles the complex parts (SAML parsing, token validation, IDP integrations)

Conclusion

Enterprise SSO used to be a feature that delayed product launches. Between understanding OAuth flows, handling SAML complexity, and building customer onboarding portals, it was weeks of work.

AI coding agents with specialized plugins collapse that timeline to minutes. But this isn't about AI writing code faster—it's about encoding expert knowledge into reusable skills that handle entire feature implementations.

The Scalekit plugin doesn't just generate boilerplate. It:

  • Understands your codebase structure
  • Queries your live environment
  • Follows security best practices
  • Creates complete, working flows

This is the new paradigm: describe the outcome, let specialized agents handle the implementation details.

Next steps:

Try it yourself: The fastest way to understand this isn't reading—it's doing. Spin up a fresh Next.js app, install the plugin, and watch Claude build your SSO flow in real-time.

The future of development isn't writing less code. It's describing what you want and having specialized agents that actually understand your domain build it for you.


Have questions? Join the Scalekit's Slack or the Claude Code community.

Top comments (0)