xiaohongshu
xiaohongshu
moai-baas-clerk-ext
Enterprise Clerk Authentication Platform with AI-powered modern identity architecture, Context7 integration, and intelligent user management orchestration for scalable applications
Full skill instructions
| Field | Value |
|---|---|
| Skill Name | moai-baas-clerk-ext |
| Version | 4.0.0 (2025-11-13) |
| Tier | Enterprise Authentication Platform Expert |
| AI-Powered | ✅ Context7 Integration, Intelligent Architecture |
| Auto-load | On demand when Clerk keywords detected |
Enterprise Clerk Authentication Platform expert with AI-powered modern identity architecture, Context7 integration, and intelligent user management orchestration for scalable applications.
Revolutionary v4.0.0 capabilities:
Automatic triggers:
Manual invocation:
# AI-powered Clerk architecture optimization with Context7
class ClerkArchitectOptimizer:
def __init__(self):
self.context7_client = Context7Client()
self.auth_analyzer = AuthenticationAnalyzer()
self.ux_optimizer = UserExperienceOptimizer()
async def design_optimal_clerk_architecture(self,
requirements: AuthenticationRequirements) -> ClerkArchitecture:
"""Design optimal Clerk architecture using AI analysis."""
# Get latest Clerk and authentication documentation via Context7
clerk_docs = await self.context7_client.get_library_docs(
context7_library_id='/clerk/docs',
topic="authentication user management organizations webauthn 2025",
tokens=3000
)
auth_docs = await self.context7_client.get_library_docs(
context7_library_id='/authentication/docs',
topic="modern auth security patterns webauthn 2025",
tokens=2000
)
# Optimize user experience flows
ux_design = self.ux_optimizer.optimize_user_flows(
requirements.user_preferences,
requirements.platform_requirements,
clerk_docs
)
# Configure security framework
security_config = self.auth_analyzer.configure_security(
requirements.security_level,
requirements.threat_model,
auth_docs
)
return ClerkArchitecture(
authentication_flows=self._design_auth_flows(requirements),
organization_setup=self._configure_organizations(requirements),
security_framework=security_config,
user_experience=ux_design,
platform_integration=self._integrate_platforms(requirements),
monitoring_setup=self._setup_monitoring(),
migration_strategy=self._create_migration_strategy(requirements)
)
// Next.js application with Clerk integration
import { ClerkProvider, SignIn, SignUp, UserButton } from '@clerk/nextjs';
import { dark } from '@clerk/themes';
import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
return (
<ClerkProvider
appearance={{
baseTheme: dark,
variables: {
colorPrimary: '#ffffff',
colorBackground: '#1a1a1a',
},
elements: {
formButtonPrimary: 'bg-blue-600 hover:bg-blue-700 text-white',
card: 'bg-gray-900 shadow-xl',
},
}}
publishableKey={process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY}
>
<Component {...pageProps} />
</ClerkProvider>
);
}
export default MyApp;
// Protected route component
import { useAuth, RedirectToSignIn } from '@clerk/nextjs';
import { useEffect } from 'react';
export default function ProtectedPage() {
const { isSignedIn, user, isLoaded } = useAuth();
if (!isLoaded) {
return <div>Loading...</div>;
}
if (!isSignedIn) {
return <RedirectToSignIn />;
}
return (
<div>
<h1>Welcome, {user.firstName || user.emailAddresses[0].emailAddress}!</h1>
<UserButton afterSignOutUrl="/" />
</div>
);
}
// Advanced organization management with Clerk
import {
ClerkProvider,
useOrganization,
useUser,
OrganizationList,
CreateOrganization,
} from '@clerk/nextjs';
export function OrganizationManagement() {
const { organization, isLoaded, membership } = useOrganization();
const { user } = useUser();
if (!isLoaded) {
return <div>Loading organization...</div>;
}
return (
<div className="organization-management">
{organization ? (
<div className="current-organization">
<h2>{organization.name}</h2>
<p>Role: {membership?.role}</p>
{/* Organization members management */}
{membership?.role === 'admin' && (
<div className="admin-panel">
<h3>Admin Controls</h3>
<OrganizationInvitation />
<MemberList />
<OrganizationSettings />
</div>
)}
{/* Regular member view */}
<div className="member-panel">
<OrganizationProjects />
<TeamCollaboration />
</div>
</div>
) : (
<div className="no-organization">
<h3>Join or Create an Organization</h3>
<OrganizationList
hidePersonal
appearance={{
elements: {
organizationPreview: 'border border-gray-700 rounded-lg p-4',
},
}}
/>
<CreateOrganization
appearance={{
elements: {
formButtonPrimary: 'bg-blue-600 hover:bg-blue-700 text-white',
},
}}
/>
</div>
)}
</div>
);
}
// Organization invitation management
async function inviteUserToOrganization(
organizationId: string,
email: string,
role: 'admin' | 'basic_member'
): Promise<void> {
try {
const response = await fetch(
`https://api.clerk.dev/v1/organizations/${organizationId}/invitations`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.CLERK_SECRET_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
email_address: email,
role: role,
disable_existing_memberships: false,
}),
}
);
if (!response.ok) {
throw new Error('Failed to send invitation');
}
return await response.json();
} catch (error) {
console.error('Error inviting user:', error);
throw error;
}
}
// Advanced WebAuthn configuration with Clerk
import { useAuth } from '@clerk/nextjs';
import { startAuthentication } from '@simplewebauthn/browser';
export function WebAuthnSecurity() {
const { user } = useAuth();
const enableWebAuthn = async () => {
try {
// Initiate WebAuthn registration
const authResp = await startAuthentication({
// Options provided by Clerk
challenge: 'random_challenge_string',
allowCredentials: [],
userVerification: 'required',
timeout: 60000,
});
// Complete registration with Clerk
const response = await fetch('/api/auth/webauthn/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
credential: authResp,
userId: user.id,
}),
});
if (response.ok) {
console.log('WebAuthn security key added successfully');
}
} catch (error) {
console.error('WebAuthn registration failed:', error);
}
};
return (
<div className="webauthn-security">
<h3>Security Keys</h3>
<button onClick={enableWebAuthn}>
Add Security Key (WebAuthn)
</button>
<SecurityKeyList />
</div>
);
}
// Backend API route for WebAuthn
import { clerkClient, getAuth } from '@clerk/nextjs/server';
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { userId } = getAuth(req);
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
if (req.method === 'POST') {
try {
const { credential } = req.body;
// Add WebAuthn credential to user
const updatedUser = await clerkClient.users.updateUser(userId, {
webauthnCredentials: [
{
publicKey: credential.response.publicKey,
id: credential.id,
type: credential.type,
transports: credential.response.transports,
}
]
});
res.status(200).json({
success: true,
message: 'Security key added successfully'
});
} catch (error) {
res.status(500).json({ error: 'Failed to add security key' });
}
} else {
res.status(405).json({ error: 'Method not allowed' });
}
}
// Real-time user experience enhancements
import { useAuth, useUser } from '@clerk/nextjs';
import { useState, useEffect } from 'react';
export function RealtimeUserExperience() {
const { user, isLoaded } = useUser();
const [onlineStatus, setOnlineStatus] = useState<'online' | 'away' | 'offline'>('online');
const [lastActivity, setLastActivity] = useState(Date.now());
useEffect(() => {
const handleActivity = () => {
setLastActivity(Date.now());
setOnlineStatus('online');
};
const checkInactivity = () => {
const inactiveTime = Date.now() - lastActivity;
if (inactiveTime > 300000) { // 5 minutes
setOnlineStatus('away');
}
if (inactiveTime > 900000) { // 15 minutes
setOnlineStatus('offline');
}
};
// Track user activity
window.addEventListener('mousemove', handleActivity);
window.addEventListener('keydown', handleActivity);
// Check inactivity periodically
const inactivityTimer = setInterval(checkInactivity, 60000);
return () => {
window.removeEventListener('mousemove', handleActivity);
window.removeEventListener('keydown', handleActivity);
clearInterval(inactivityTimer);
};
}, [lastActivity]);
if (!isLoaded) {
return <div>Loading user experience...</div>;
}
return (
<div className="user-experience">
{/* Real-time presence indicator */}
<div className={`status-indicator ${onlineStatus}`}>
<span className="status-dot"></span>
<span className="status-text">{onlineStatus}</span>
</div>
{/* Adaptive UI based on user preferences */}
{user?.publicMetadata?.theme && (
<div className="theme-applied">
Theme: {user.publicMetadata.theme}
</div>
)}
{/* Personalized features */}
<PersonalizedFeatures user={user} />
</div>
);
}
// M2M (Machine-to-Machine) authentication
export function M2MAuthentication() {
const [m2mToken, setM2mToken] = useState<string | null>(null);
const generateM2MToken = async () => {
try {
const response = await fetch('/api/auth/m2m/token', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.CLERK_SECRET_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: 'service_account',
expires_in_seconds: 3600,
}),
});
const data = await response.json();
setM2mToken(data.jwt);
} catch (error) {
console.error('M2M token generation failed:', error);
}
};
return (
<div className="m2m-authentication">
<h3>Machine-to-Machine Authentication</h3>
<button onClick={generateM2MToken}>
Generate M2M Token
</button>
{m2mToken && (
<div className="token-display">
<p>Token generated successfully</p>
<code>{m2mToken.substring(0, 20)}...</code>
</div>
)}
</div>
);
}
create_user(email, password) - Create new user accountcreate_organization(name, slug) - Create organizationinvite_to_organization(org_id, email, role) - Invite user to organizationadd_webauthn_credential(user_id, credential) - Add security keygenerate_m2m_token(template) - Generate machine-to-machine tokenget_latest_clerk_documentation() - Official Clerk docs via Context7analyze_modern_auth_patterns() - Modern authentication via Context7optimize_user_experience() - UX best practices via Context7moai-baas-foundation (Enterprise BaaS architecture patterns)moai-security-api (API security and authorization)moai-foundation-trust (Security and compliance)moai-baas-auth0-ext (Enterprise authentication comparison)moai-domain-frontend (Frontend auth integration)moai-essentials-perf (Authentication performance optimization)moai-domain-backend (Backend auth integration)moai-security-encryption (Data protection and encryption)End of Skill | Updated 2025-11-13
End of Enterprise Clerk Authentication Platform Expert v4.0.0
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience