Building a Multi-tenant Authentication System for CM64 Startup Studio
Today's work focused on implementing a comprehensive authentication system for CM64 Startup Studio, a framework that enables developers to build and deploy web applications using JSON configurations.
Project Context
CM64 Startup Studio is an innovative web framework that uses JSON structures to define routes, pages, and components. The platform consists of two main parts: a developer console (/.studio) for building applications and the actual web applications that end-users interact with.
The Challenge
We needed to implement two separate but coexisting authentication systems:
- One for developers accessing the studio console
- Another for end-users of applications built with the framework
The main complexity lay in maintaining clear separation between these systems while keeping the implementation simple and secure.
Our Solution
We implemented a domain-based authentication system using magic links as the primary authentication method. Here's a simplified version of our core authentication flow:
// Magic Link Authentication Flow
export async function createSession(user, startupId) {
const token = await new SignJWT({
userId: user._id.toString(),
startupId: startupId,
email: user.email
})
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('24h')
.setIssuedAt()
.sign(new TextEncoder().encode(JWT_SECRET));
cookies().set('webapp_auth_token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24
});
return token;
}
The system uses:
- JWT for secure session management
- Domain-specific authentication settings
- Separate authentication paths for studio and web applications
- In-memory rate limiting for security
Key Insights
- Separating authentication concerns by domain provides better security and maintainability
- Magic links offer a superior user experience while eliminating password management
- Using Next.js App Router's file-based routing helped maintain clear separation between studio and webapp authentication flows
Practical Takeaways
Developers working on multi-tenant systems can learn several valuable lessons from our implementation:
- How to maintain separate authentication systems in a single codebase
- Techniques for implementing magic link authentication
- Strategies for handling authentication in Next.js App Router
- Methods for implementing rate limiting without external dependencies
Next Steps
Future improvements will include:
- Adding support for additional authentication methods (Google, Web3)
- Implementing email templates for magic links
- Adding session management features
- Enhancing security with additional rate limiting and monitoring
The authentication system provides a foundation for building secure, user-friendly applications while maintaining clear separation between developer and end-user authentication flows.