🚀 A collaborative, cloud-based coding platform for interview preparation and social coding
🌐 Live Demo • 📖 Technical Manual • 🐛 Report Bug • 💡 Request Feature
- About
- Features
- Tech Stack
- Getting Started
- Collaborative Editor
- Authentication
- Roadmap
- Project Structure
- Troubleshooting
- Contributing
S‑code is a collaborative, cloud-based coding platform built with Next.js that blends real-time interview preparation with social coding to make learning more engaging and less isolating. It offers a secure, streamlined authentication system, role-based room access, and a scalable architecture for collaborative code editing.
Code with friends. Learn faster. Ace interviews.
S‑code makes coding practice feel like multiplayer gaming — secure, fast, and frustration-free. Whether you're preparing for technical interviews, practicing algorithms, or collaborating on projects, S‑code provides the tools you need to succeed together.
Frontend & Framework
- Next.js 16 + TypeScript 5.9 (App Router)
- React 19 with modern hooks
- Tailwind CSS v4 + Radix UI for styling
- Monaco Editor (Self-hosted assets)
Backend & Database
- MongoDB with Node.js driver (centralized connection)
- Upstash Redis for caching, rate limiting, and token storage
- RESTful API design with Next.js API routes
Real-time Collaboration
- Y.js for Conflict-free Replicated Data Types (CRDTs)
- WebSocket server for real-time document synchronization
- IndexedDB for offline persistence
Video Conferencing
- Stream Video SDK for real-time video calls
- Camera and microphone permission handling
- Pre-join preview with device controls
- Block/kick event handling for moderation
Authentication & Security
- NextAuth.js v5 for OAuth (Google, GitHub)
- bcrypt for password hashing
- jose for JWT token management
- Cryptographically secure refresh tokens (crypto.randomBytes)
- HttpOnly cookies for secure token storage
- Zod + react-hook-form for validation
Email & Communication
- Resend for transactional emails
- Email verification system with Redis-backed tokens
AI Integration
- Google Gemini SDK (
@google/genai) for AI-powered coding assistance - Context-aware code analysis and suggestions
- Smart retry logic with error handling
Development Tools
- ESLint for code linting
- TypeScript for type safety
- pnpm for efficient package management
Privacy-first auth and token hygiene:
- OAuth Integration: Google and GitHub sign-in via NextAuth.js v5
- Email/password signup with domain restriction
- Email verification with short‑lived tokens (stored in Redis)
- Cryptographic tokens: Random bytes for unpredictable refresh tokens
- Secure, HttpOnly refresh tokens in cookies (no access tokens in localStorage)
- Unified auth middleware: Supports both OAuth and custom auth
- Middleware-protected routes with server-side refresh validation
- Rate limiting hooks in place to prevent brute-force attacks
- Strong password hashing (bcrypt)
- Room Password Protection: Cryptographically secure room passwords hashed with bcrypt on creation and verified with
bcrypt.compareon join - CSRF Origin Protection: Validation of request origin and referer on all protected state-changing API endpoints
- Security headers: Strict-Transport-Security (HSTS), Content-Security-Policy (CSP) tailored for WebSockets/APIs, X-Frame-Options, X-Content-Type-Options, and Permissions-Policy
- Permissions-Policy: Camera and microphone access enabled for same-origin (video calls)
- User enumeration prevention: Generic error messages on login/forgot-password
- Session invalidation on password reset (logout all devices)
- Sensitive Data Isolation: Complete exclusion of passwords/credentials from all room detail and public API response models
- OAuth Support: Google and GitHub sign-in via NextAuth.js v5
- Secure Registration: Email/password signup with domain restrictions
- Email Verification: Short-lived tokens stored in Redis for verification
- Session Management: HttpOnly refresh tokens with automatic rotation
- Unified Auth Middleware: Single auth layer for OAuth and custom auth
- Protected Routes: Middleware-based route protection
- Rate Limiting: Brute-force attack prevention
- Password Security: Strong bcrypt hashing
- Security Headers: XSS, clickjacking, and MIME-sniffing protection
- Real-time Synchronization: Y.js CRDTs for conflict-free collaboration
- Multi-language Support: JavaScript, TypeScript, Python, Go, Java, C, C++
- Monaco Editor: Full-featured code editor with syntax highlighting and self-hosted assets to eliminate external CDN dependencies and latency
- Code Execution: Run code directly in the browser with output display
- WebSocket Integration: Seamless real-time updates
- Optimized Performance: Removed cursor tracking for cleaner console logs
- Room Creation: Schedule and create coding sessions
- Room Types: Interview prep, mock interviews, pair programming
- Privacy Controls: Public and private room options
- Join System: Easy room joining with validation
- Host Controls: Manage participants and session settings
- Session Overview: Track your coding activities
- Room Management: Create, schedule, and join rooms
- User Profile: Manage account settings and preferences
- Activity Tracking: Monitor your coding progress
- Quick Access: Easy navigation to recent rooms
- Multi-page Notes: Create up to 10 pages per room (numbered 0-9)
- IndexedDB Storage: Persistent local storage with roomId + pageNumber
- Editable Titles: Customize page titles for better organization
- Character Limit: 5000 characters per page with live counter
- Auto-save: Automatic saving every 5 minutes
- Page Management: Create, delete, and switch between pages
- Smart Numbering: Automatically fills gaps when pages are deleted
- Gemini Integration: Powered by Google's Gemini 2.0 Flash
- Context-Aware: Analyzes your current code and language
- Smart Retry Logic: Automatic retry with exponential backoff
- Code-Focused: Only responds to programming-related questions
- Formatted Responses: Clean, readable output with code examples
- Rate Limited: Prevents abuse with message length limits
- Stream Video SDK: Real-time video conferencing in coding sessions
- Pre-join Preview: Test camera and microphone before joining
- Device Management: Toggle camera/mic with visual feedback
- Permission Handling: Smart browser permission detection and user guidance
- Permission UI: Clear instructions when permissions are denied or prompting
- Block/Kick Events: Host moderation capabilities for managing participants
- Automatic Cleanup: Proper resource disposal to prevent memory leaks
- Rejoin Support: Seamless reconnection after leaving or being kicked
- Permissions Policy: Configured to allow camera/mic for same-origin (security compliant)
- Dynamic Sitemap & Robots: Generated dynamically to prioritize indexable public pages while restricting crawler access on auth, chat, or room workspaces.
- Search & Bot Crawler Friendliness: Optimized rules to allow search, social preview, and SEO visibility bots to crawl meta tags.
- Humans.txt & Security.txt: Configured
/humans.txtfor contributor credits, and/.well-known/security.txtfor responsible vulnerability disclosure. - Static Asset Cache Hashing: Automated Cache-Control headers for media and script assets to optimize browser performance.
- Technical Difficulties Banner: Configuration-driven global alert system to notify active users of ongoing maintenance, system outages, or degraded features with customizable alert persistency. See Technical Difficulties Banner Manual.
- Type Safety: Full TypeScript implementation
- Form Validation: Zod schemas with react-hook-form
- Error Handling: Comprehensive error management
- API Design: RESTful API with predictable responses
- Responsive Design: Mobile-friendly interface
- Client-Side Caching: UserCache for optimized data fetching
- Real-time collaborative code rooms (Monaco + Y.js)
- Multi-language support (JavaScript, TypeScript, Python, Go, Java, C, C++)
- Code execution engine with output display
- Notes system with IndexedDB storage (up to 10 pages per room)
- Room creation and management system
- Registration form refactoring with modular components
- Secure authentication system with email verification
- Dashboard interface with session tracking
- Explore page for discovering public coding sessions
- Error boundary implementation for improved reliability
- Performance optimization: Removed awareness/cursor tracking
- Comprehensive development documentation and Git workflow guides
- AI Chat Integration: Gemini-powered coding assistant with retry logic
- Authentication Improvements: Real-time navbar updates, token refresh optimization
- Profile System: Infinite loop fixes, cache management, avatar handling
- UI/UX Enhancements: Responsive dashboard cards, improved skeleton loading
- OAuth Integration: Google and GitHub sign-in via NextAuth.js v5
- Security Hardening: Cryptographic tokens, security headers, user enumeration prevention
- Unified Auth Middleware: Single auth layer supporting OAuth and custom authentication
- Profile Privacy: Limited public profile exposure, full data only for own profile
- Video Call Integration: Stream Video SDK with pre-join preview and device management
- Permission Handling: Browser camera/microphone permission monitoring and user guidance
- Video Moderation: Block/kick event handling for room hosts
- Security Hardening: Implemented CSRF origin protection, HSTS headers, secure CSP connection routing, and room password bcrypt hashing
- SEO & Bot Management: Added humans.txt, security.txt, dynamic sitemap/robots, and crawler optimizations
- Asset Self-Hosting: Transitioned Monaco Editor assets to local route hosting for zero-latency loading
- Global Notices: Implemented a flexible Technical Difficulties Banner component for system-wide announcements
- Room roles & permissions system
- Enhanced UI/UX improvements
- Performance optimizations
- Advanced video features (screen sharing, recording)
- Authentication Enhancements
- Discord OAuth integration
- Multi-factor authentication (TOTP)
- Device-based trust and session management
- Collaboration Features
- Screen sharing capabilities
- Real-time chat system
- Code review and commenting
- Video call recording and playback
- Room Management
- Advanced room templates
- Automated interview scheduling
- Recording and playback
- Custom coding challenges
- Developer Experience
- Docker containerization
- CI/CD pipeline setup
- Mobile responsive design
- PWA capabilities
- Analytics & Insights
- Coding session analytics
- Performance metrics
- Learning progress tracking
- Interview feedback system
- Node.js 18+ (tested with Node.js 20)
- pnpm (recommended) or npm
- MongoDB database (local or cloud)
- Redis instance (Upstash recommended)
- Clone the repository
git clone https://github.com/Sudarshan7a/scode.git
cd scode- Install dependencies
# Using pnpm (recommended)
pnpm install
# Or using npm (with legacy peer deps for compatibility)
npm install --legacy-peer-deps- Configure environment
Create .env.local in the root directory:
# Optional public API URL
NEXT_PUBLIC_API_URL=http://localhost:3000/api
# Database
MONGODB_URI=mongodb+srv://<user>:<pass>@<cluster>/<db>?retryWrites=true&w=majority
MONGODB_DB=scode
# Authentication
JWT_SECRET=your-super-secure-jwt-secret-here
# Upstash Redis (used by rate limiter & verify tokens)
UPSTASH_REDIS_REST_URL=your-upstash-redis-rest-url-here
UPSTASH_REDIS_REST_TOKEN=your-upstash-redis-rest-token-here
# Email Service
RESEND_API_KEY=your-resend-api-key-here
MY_DOMAIN=http://localhost:3000
# AI Assistant (Optional)
GEMINI_API_KEY=your-gemini-api-key-here
# OAuth Providers (NextAuth.js)
AUTH_SECRET=your-auth-secret-here # Generate with: npx auth secret
AUTH_GOOGLE_ID=your-google-client-id
AUTH_GOOGLE_SECRET=your-google-client-secret
AUTH_GITHUB_ID=your-github-client-id
AUTH_GITHUB_SECRET=your-github-client-secret
# Stream Video (for video calls)
NEXT_PUBLIC_STREAM_API_KEY=your-public-stream-api-key-here
STREAM_API_KEY=your-stream-api-key-here
STREAM_API_SECRET=your-stream-api-secret-here- Start the WebSocket server (for real-time collaboration)
cd websocket
pnpm install
npx y-websocket- Run the development server
# In the root directory
pnpm dev- Open your browser Navigate to http://localhost:3000
docker-compose up -dSignup
- Client validates with Zod; server validates again
- Email domains must be in
allowedEmailDomains(e.g. gmail.com, outlook.com, ...) - On success, user is created with
emailVerified=falseand a verification email is sent
Verify email
- Route:
GET /api/auth/verify?token=... - Token stored in Redis with 10-minute TTL; upon success, user
emailVerified=true - A refresh session is now issued automatically and the user is redirected straight to the dashboard
- UI page:
app/verify-email/[token]/page.tsxhandles status + redirect
Login
- Verifies
passwordHashagainst input - If
emailVerified=false, blocks login and resends a verification email - On success, issues (rotated) refresh token via centralized
issueRefreshSessionutil and sets cookies
Tokens
- Refresh token: stored in Mongo with fields
{ userId, token, createdAt, expiresAt }(issued & optionally rotated bylib/refreshSession.ts) - Access token: short-lived JWT issued on demand from refresh token
The real-time collaborative editor is built with Monaco Editor and Y.js for seamless multiplayer coding:
Supported Languages
- JavaScript
- TypeScript
- Python
- Go
- Java
- C
- C++
Key Features
- Real-time synchronization using Y.js CRDTs (Conflict-free Replicated Data Types)
- WebSocket-based collaboration with automatic conflict resolution
- Offline persistence with IndexedDB
- Language switching with syntax highlighting
- Resizable panels for optimal workspace layout
Architecture
CollaborativeEditor.tsx: Main editor component with language selectionlib/monaco/monacoEnvironment.ts: Monaco editor configuration- WebSocket server: Handles Y.js document synchronization
- IndexedDB persistence: Stores documents locally for offline access
The editor dynamically loads heavy dependencies (Monaco, Y.js workers) only when needed to maintain fast initial page loads.
Central types: types/mongodbTypes.ts
Mongo validators (typed as TS constants): types/mogodbValidation.ts
- Users: letters-only
name, allowed email domains,emailVerifiedboolean - Refresh tokens: camelCase fields (
userId,createdAt,expiresAt) - Rooms, saved notes/code, user activity: basic shapes provided
Connection: lib/mongodb.ts
- Exposes camelCase collection handles (e.g.
usersCollection) - Honors
MONGODB_DBif set; logs connected DB in dev
app/ # Next.js App Router pages
├── api/ # API routes (auth, etc.)
├── dashboard/ # Dashboard pages
├── room/ # Collaborative room pages
└── ... # Auth pages (login, signup, verify)
lib/ # Database, auth, and utility helpers
├── monaco/ # Monaco editor environment setup
├── mongodb.ts # Database connection
├── notesDB.ts # IndexedDB for notes storage
├── refreshSession.ts # Session management
└── ... # Other utilities
types/ # TypeScript types & validators
├── mongodbTypes.ts # Database schema types
├── mogodbValidation.ts # Validation rules
└── ...
components/ # UI and feature components
├── dashboard/ # Dashboard-specific components
├── joinRoom/ # Room-specific components
│ ├── notes/ # Notes system components
│ └── gemmini/ # AI chat integration
├── custom/
│ └── schedule/ # Registration forms (modular)
│ ├── dialogs/ # Form dialogs
│ ├── fields/ # Reusable form fields
│ ├── forms/ # Complete form components
│ └── schemas/ # Validation schemas
├── ui/ # Reusable UI components
└── ...
websocket/ # Y.js WebSocket server for collaboration
public/ # Static assets
- Allowed domains: update
allowedEmailDomainsintypes/mogodbValidation.ts - Email template:
lib/EmailTemplate.ts(copy, CTA, expiry note) - Verification token TTL:
lib/verifyToken.ts(Redis set with EX 600) - WebSocket server port: Default is 1234, can be configured in
websocket/server.js
Installation Issues
- Dependency conflicts with
react-day-picker- Use
npm install --legacy-peer-depsinstead of regular npm install - Or use
pnpm installwhich handles peer dependencies better
- Use
- Node.js version compatibility
- Ensure you're using Node.js 18+ (tested with Node.js 20)
- Check version with
node --version
- WebSocket server fails to start
- Navigate to
websocket/directory first:cd websocket - Install WebSocket dependencies:
npm installorpnpm install - Start server:
npx y-websocket
- Navigate to
Authentication Issues
- Domain not allowed on signup
- Error appears under the email field: update
allowedEmailDomainsto include your domain
- Error appears under the email field: update
- “Document failed validation” on user insert
namemust be letters-only (A–Z); ensure username sanitization or adjust validator
- No verification email
- Check
RESEND_API_KEYandMY_DOMAINURL; Resend may require a verified sender domain
- Check
- Refresh token errors / redirects to login
- Verify middleware and
/api/auth/verify-refresh-tokenendpoint; check tokenexpiresAt
- Verify middleware and
Collaboration Issues
- Room connection fails
- Ensure WebSocket server is running:
cd websocket && npx y-websocket - Check if port 1234 is available
- Verify network connectivity
- Ensure WebSocket server is running:
- Unable to join room
- Check room ID is correct
- Ensure room exists and is accessible
- Try refreshing the page
- Performance issues in large rooms
- Close unnecessary browser tabs
- Check browser DevTools for memory usage
- Consider limiting concurrent users per room
This repository includes a comprehensive Git audit system to help developers learn best practices:
# Run comprehensive audit
npm run audit:git
# Run specific audits
npm run audit:commits # Analyze commit patterns
npm run audit:branches # Check branch strategy
npm run audit:secrets # Scan for leaked secrets- Commit Quality Analysis - Message clarity, frequency, and atomicity
- Branch Strategy Review - Naming conventions and workflow
- Secret Detection - Prevent accidentally committed credentials
- Educational Resources - Learn Git best practices step by step
- Progress Tracking - JSON reports and scoring system
See git-audit/README.md for full documentation and git-audit/educational/learning-path.md for a beginner-friendly improvement guide.
See realistic-commit-plan.md for a batch script that stages and backdates a realistic series of commits across the past weeks.
This repository includes comprehensive tools to help beginners learn Git best practices and avoid common mistakes:
# Run repository health check
npm run audit:repo
# Validate a commit message
npm run audit:commit "feat(auth): add user login validation"
# View all Git learning resources
npm run help:git- Git Best Practices - Comprehensive guide with examples
- Learning Checklist - Progressive skill-building path
- Repository Scorecard - Self-assessment tool
- Development Setup - Tool configuration guide
- Git Examples - Before/after examples of common mistakes
scripts/git-audit.sh- Comprehensive repository health checkscripts/validate-commit.js- Commit message validation- Scoring system for repository hygiene
- Educational examples and templates
Perfect for beginners who want to learn professional Git workflows and avoid common pitfalls!
Made with Next.js App Router, MongoDB, and a secure, explicit auth flow.
We welcome contributions! Please read our Contributing Guidelines before submitting PRs.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Commit using conventional commits:
git commit -m "feat: add amazing feature" - Push to your branch:
git push origin feature/amazing-feature - Open a Pull Request
Found a bug? Please open an issue with:
- Steps to reproduce
- Expected vs actual behavior
- Browser/OS information
- Console errors (if any)
Have an idea? We'd love to hear it! Open a feature request with:
- Use case description
- Proposed solution
- Alternative solutions considered
This project is licensed under the MIT License - see the LICENSE file for details.
- Monaco Editor for the excellent code editor
- Y.js for real-time collaboration
- Next.js for the amazing React framework
- Radix UI for accessible UI components
⭐ Star this repository if you find it helpful!