English-First PWA with PayPal, Supabase & Viral Features
A production-ready template for building scalable web applications with authentication, payments, and social sharing.
- Multi-Provider OAuth: Google, Apple, GitHub integration
- Guest Mode: 3-day trial with seamless upgrade
- Data Migration: Automatic guest-to-member data transfer
- Session Management: Secure JWT with refresh tokens
- Row Level Security: Supabase RLS for data protection
- PayPal Subscriptions: Multiple plans (Premium, Pro)
- Subscription Management: Cancel, upgrade, downgrade
- Payment Security: PCI-compliant processing
- Webhook Handling: Real-time payment status updates
- Grace Periods: 3-day grace period for expired subscriptions
- Daily Tracking: Mood-based achievement logging
- Streak Calculation: Current and longest streaks
- Category System: Health, Fitness, Learning, Career, etc.
- Sharing Features: Social media integration
- Premium Categories: Business, Finance (subscription-only)
- Offline First: Works without internet connection
- App Installation: Native app-like experience
- Push Notifications: Real-time updates
- Background Sync: Offline actions sync when online
- App Shortcuts: Quick actions from home screen
- Real-time Updates: Supabase WebSocket integration
- Infinite Scroll: Virtualized lists for large datasets
- Optimistic Updates: Immediate UI feedback
- Image Optimization: Next.js built-in optimization
- Bundle Analysis: Built-in bundle size monitoring
- Content Security Policy: XSS protection
- HTTPS Everywhere: Secure connections only
- Rate Limiting: Abuse prevention
- Input Validation: Server-side validation
- Device Fingerprinting: Bot detection
- Node.js 18+ and npm
- Supabase account
- PayPal Developer account
- Google OAuth credentials
git clone https://github.com/your-username/global-app-template.git
cd global-app-template/variants/nextjs
npm installcp .env.example .env.localFill in your environment variables:
# Supabase
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
# PayPal
NEXT_PUBLIC_PAYPAL_CLIENT_ID=your_paypal_client_id
PAYPAL_CLIENT_SECRET=your_paypal_client_secret
# Google OAuth
NEXT_PUBLIC_GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
# Security
JWT_SECRET=your_jwt_secret_minimum_32_characters
ENCRYPTION_KEY=your_encryption_key_32_bytes# Run the Supabase migrations
npx supabase db reset
npx supabase db pushnpm run devVisit http://localhost:3000 to see your app!
- Go to Supabase
- Create new project
- Wait for database to be ready
- Copy your project URL and anon key
Run the SQL files in this order:
database/schema.sql- Main schemadatabase/policies.sql- Security policiesdatabase/functions/common_functions.sql- Utility functions
- Go to Authentication > Settings
- Enable Google provider
- Add your Google OAuth credentials
- Set redirect URLs:
- Development:
http://localhost:3000/auth/callback - Production:
https://yourapp.com/auth/callback
- Development:
- Go to PayPal Developer
- Create new app
- Choose "Merchant" for subscriptions
- Copy Client ID and Secret
Use PayPal's API or dashboard to create these plans:
premium-monthly: $9.99/monthpremium-yearly: $99.99/yearpro-monthly: $19.99/monthpro-yearly: $199.99/year
Set up webhooks for these events:
BILLING.SUBSCRIPTION.ACTIVATEDBILLING.SUBSCRIPTION.CANCELLEDBILLING.SUBSCRIPTION.SUSPENDEDPAYMENT.SALE.COMPLETED
Webhook URL: https://yourapp.com/api/webhooks/paypal
src/
βββ domain/ # Business logic
β βββ entities/ # Domain entities
β βββ repositories/ # Repository interfaces
βββ application/ # Use cases
β βββ usecases/ # Business use cases
βββ infrastructure/ # External concerns
β βββ auth/ # Authentication services
β βββ payment/ # Payment processing
β βββ storage/ # Database integration
βββ presentation/ # UI layer
βββ components/ # React components
βββ hooks/ # Custom React hooks
βββ pages/ # Next.js pages
- Testability: Business logic isolated from frameworks
- Maintainability: Clear separation of concerns
- Scalability: Easy to add new features
- Flexibility: Swap implementations without breaking core logic
npm run dev # Start development server
npm run build # Build for production
npm run start # Start production server
npm run lint # Run ESLint
npm run lint:fix # Fix ESLint issues
npm run type-check # TypeScript type checking
npm run test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage# Run all tests
npm test
# Run integration tests
npm run test:integration
# Run with coverage
npm run test:coverageANALYZE=true npm run buildUsers can install the app on:
- Mobile: "Add to Home Screen"
- Desktop: "Install App" in browser
- iOS: Safari "Add to Home Screen"
- β View cached achievements
- β Create new achievements (syncs when online)
- β Navigate between pages
- β View profile information
- β Authentication (requires internet)
- β Payment processing (requires internet)
- Quick Achievement: Add achievement instantly
- Statistics: View your progress
- Share Progress: Share achievements
- Profile: Manage account settings
- Push code to GitHub
- Import project in Vercel
- Add environment variables
- Deploy automatically
# Build image
docker build -t global-app-template .
# Run container
docker run -p 3000:3000 global-app-templateNODE_ENV=production
NEXT_PUBLIC_APP_URL=https://yourapp.com
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
WEBHOOK_SECRET=your_webhook_secret// Guest user registration
const guestUser = await registerGuestUseCase.execute({
deviceId: 'device-123',
fingerprint: deviceFingerprint
});
// Google authentication with data migration
const authenticatedUser = await googleAuthUseCase.execute({
googleToken: 'google-token',
deviceInfo: deviceInfo,
guestDataToMigrate: {
guestToken: guestUser.tempToken,
achievements: guestAchievements
}
});// Create new achievement
const achievement = await createAchievementUseCase.execute({
userId: 'user-123',
title: 'Completed morning workout',
description: '30 minutes of cardio and strength training',
category: 'fitness',
moodLevel: 4
});// PayPal subscription component
<PayPalSubscriptionButton
planId="premium-monthly"
onSuccess={(subscriptionId, details) => {
console.log('Subscription created:', subscriptionId);
}}
onError={(error) => {
console.error('Payment failed:', error);
}}
onCancel={() => {
console.log('Payment cancelled');
}}
/>- Update
useSupabaseAuthhook - Add provider to Supabase settings
- Create provider-specific use case
- Add UI components
// Update Achievement entity
const CUSTOM_CATEGORIES = ['work', 'hobby', 'family'];
// Update validation in CreateAchievementUseCase
private validateCategory(category: string) {
const validCategories = [...DEFAULT_CATEGORIES, ...CUSTOM_CATEGORIES];
// ... validation logic
}// Update subscription plans
const SUBSCRIPTION_PLANS = {
'enterprise-monthly': { price: 49.99, interval: 'month' },
'enterprise-yearly': { price: 499.99, interval: 'year' }
};- 34 files created
- 5,915+ lines of TypeScript code
- 100% TypeScript coverage
- Clean Architecture implementation
- Production-ready configuration
Build Errors
# Clear Next.js cache
rm -rf .next
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm installSupabase Connection Issues
- Verify environment variables
- Check Supabase service status
- Ensure correct RLS policies
PayPal Integration Issues
- Verify webhook endpoints
- Check PayPal app settings
- Monitor webhook delivery logs
PWA Issues
- Clear browser cache
- Check service worker registration
- Verify HTTPS in production
MIT License - see LICENSE for details.
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
- π Documentation
- π Issue Tracker
- π¬ Discussions
- π§ Email: support@yourapp.com
Built with β€οΈ using Next.js, Supabase, and PayPal