XSight - A production-grade Shopify analytics and CRM platform with advanced RFM segmentation, real-time sync progress tracking, and comprehensive customer insights.
What's covered:
- ✅ Shopify OAuth integration and store connection
- ✅ Real-time data sync with WebSocket progress tracking
- ✅ RFM segmentation and customer analytics
- ✅ Custom segment builder with complex rules
- ✅ Multi-tenancy and deployment architecture
- RFM Analysis: Recency, Frequency, Monetary value segmentation
- Churn Prediction: Identify at-risk customers before they leave
- Cohort Analysis: Track customer behavior over time
- Custom Segments: Build dynamic customer segments with complex rules
- Revenue Analytics: Track orders, revenue, and customer lifetime value
- WebSocket Progress Tracking: See live sync progress with percentage and step info
- BullMQ Job Processing: Reliable background job queue with Redis
- Webhook Processing: Automatic real-time updates via Shopify webhooks
- Incremental Sync: Efficient sync with cursor-based pagination
- JWT Authentication: Secure HTTP-only cookie-based auth
- Tenant Isolation: Complete data separation between stores
- Rate Limiting: Per-tenant API rate limits with Redis
- HMAC Verification: Secure webhook validation
- Next.js 14 Frontend: Server-side rendering, React 18, App Router
- Express.js Backend: RESTful API with TypeScript
- Prisma ORM: Type-safe database access with PostgreSQL
- Redis: Caching, rate limiting, job queue, Pub/Sub
- Socket.IO: Real-time WebSocket communication
- Node.js: >= 20.0.0
- pnpm: >= 9.0.0 (package manager)
- PostgreSQL: >= 14.0 (database)
- Redis: >= 7.0 (cache, queue, Pub/Sub)
- Shopify Partner Account: For app credentials
├── server/ # Backend Express.js API
│ ├── config/ # Database, Redis, environment config
│ ├── lib/ # Utilities (JWT, crypto, logger, cache, sync-progress)
│ ├── middleware/ # Auth, rate limiting, error handling
│ ├── routes/ # API endpoints (v1, auth, webhooks)
│ ├── services/ # Business logic
│ │ ├── analytics/ # RFM, churn prediction, cohort analysis
│ │ ├── queue/ # BullMQ queue definitions
│ │ ├── segment/ # Segment management and rules
│ │ ├── shopify/ # Shopify API integration
│ │ ├── scheduler.ts # Cron jobs and scheduled tasks
│ │ └── worker.ts # Background job processor
│ ├── websocket/ # Socket.IO real-time server
│ └── index.ts # Server entry point
├── src/ # Frontend Next.js app
│ ├── app/ # Next.js pages and layouts
│ │ ├── app/ # Dashboard pages
│ │ ├── auth/ # Login/signup pages
│ │ ├── connect/ # Shopify connection flow
│ │ └── page.tsx # Landing page
│ ├── components/ # React components
│ │ ├── analytics/ # Analytics charts and cards
│ │ ├── customers/ # Customer list and details
│ │ ├── segments/ # Segment builder and management
│ │ ├── sync/ # Sync status and progress
│ │ └── ui/ # shadcn/ui components
│ ├── hooks/ # React hooks
│ │ ├── use-api.ts # API queries and mutations
│ │ ├── use-auth.tsx # Authentication context
│ │ ├── use-websocket.tsx # WebSocket real-time updates
│ │ └── use-shop.tsx # Shopify shop context
│ └── lib/ # Frontend utilities
├── prisma/ # Database schema and migrations
├── docs/ # Documentation
└── public/ # Static assets
git clone <repository-url>
cd shopify-app-template-react-router-main
pnpm installCreate .env file in the root directory:
# Database
DATABASE_URL="postgresql://user:password@localhost:5432/xsight"
# Redis (Upstash recommended for production)
REDIS_URL="redis://localhost:6379"
# Shopify App Credentials
SHOPIFY_API_KEY="your_api_key"
SHOPIFY_API_SECRET="your_api_secret"
SHOPIFY_APP_URL="https://your-domain.com"
SCOPES="read_customers,read_orders,read_products"
# JWT Secret (generate with: openssl rand -base64 32)
JWT_SECRET="your-jwt-secret-key"
# Frontend URL
FRONTEND_URL="http://localhost:3001"
# Node Environment
NODE_ENV="development"
# Server Port
PORT=3000
# Encryption Key (generate with: openssl rand -base64 32)
ENCRYPTION_KEY="your-encryption-key"
# Sentry (optional)
SENTRY_DSN="your-sentry-dsn"# Generate Prisma client
pnpm prisma generate
# Run migrations
pnpm prisma migrate dev
# (Optional) Seed database
pnpm db:seed# Start all services (backend, worker, frontend)
pnpm dev
# Or start individually:
pnpm dev:server # Backend API (port 3000)
pnpm dev:worker # Background worker
pnpm dev:client # Frontend (port 3001)pnpm add socket.io socket.io-client js-cookie
pnpm add -D @types/js-cookie- Express.js: Web server and API framework
- Prisma: Type-safe ORM with PostgreSQL
- BullMQ: Job queue with Redis
- Socket.IO: WebSocket server for real-time updates
- Pino: Structured JSON logging
- Argon2: Password hashing
- JWT: Stateless authentication
- Next.js 14: React framework with App Router
- TanStack Query: Data fetching and caching
- shadcn/ui: Accessible component library
- Tailwind CSS: Utility-first styling
- Recharts: Data visualization
- GSAP: Animations
- PostgreSQL: Primary database
- Redis: Cache, job queue, rate limiting, Pub/Sub
- Upstash: Managed Redis (recommended for production)
- Vercel: Frontend hosting (recommended)
- Railway: Backend hosting (recommended)
Complete system architecture showing data flow, services, and integrations
┌─────────────────────────────────────────────────────────────────┐
│ Client Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Next.js 14 │ │ React Query │ │ Socket.IO │ │
│ │ (Port 3001) │ │ + Zustand │ │ Client │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
↕ HTTPS
┌─────────────────────────────────────────────────────────────────┐
│ Backend Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Express.js │ │ Socket.IO │ │ BullMQ │ │
│ │ REST API │ │ Server │ │ Worker │ │
│ │ (Port 3000) │ │ (WebSocket) │ │ (Background)│ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
↕
┌─────────────────────────────────────────────────────────────────┐
│ Data & Queue Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ PostgreSQL │ │ Redis │ │ Shopify │ │
│ │ (Railway) │ │ (Upstash) │ │ Admin API │ │
│ │ + Prisma │ │ + Pub/Sub │ │ + Webhooks │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
Real-time data synchronization flow with WebSocket progress updates
| Decision | Rationale |
|---|---|
| Monorepo Structure | Single repo for frontend + backend simplifies development and deployment |
| Redis Pub/Sub | Enables real-time progress updates across worker and API server |
| BullMQ Job Queue | Reliable background processing with retry logic and persistence |
| WebSocket + REST | WebSocket for real-time updates, REST fallback for reliability |
| Prisma ORM | Type-safe queries, automatic migrations, multi-tenancy support |
| HTTP-only Cookies | Secure JWT storage, prevents XSS attacks |
Sequence diagram showing WebSocket-based progress tracking
XSight implements a sophisticated real-time progress tracking system:
- Trigger Sync: User clicks "Sync Now"
- Generate syncRunId: Server creates unique ID and stores in Redis
- Queue Jobs: BullMQ queues customer and order sync jobs
- Worker Processing: Background worker processes records, updates Redis every 500ms
- Redis Pub/Sub: Progress published to
sync-progresschannel - Socket.IO Broadcast: WebSocket server receives and broadcasts to clients
- Frontend Updates: React component shows live progress bar
- Completion: Cache invalidated, fresh data loaded automatically
Key Features:
- Throttled updates (max 2/sec) to prevent Redis spam
- Multi-tenancy with room-based isolation
- REST fallback for WebSocket failures
- Automatic cleanup with 24-hour TTL
Multi-layered security approach with tenant isolation
- HTTP-only Cookies: JWT tokens stored securely
- HMAC Verification: Shopify webhook validation
- Tenant Isolation: Row-level security with tenant ID
- Rate Limiting: Per-tenant API limits with Redis
- Encrypted Tokens: Shopify access tokens encrypted at rest (AES-256-GCM)
- CORS: Strict origin validation
- Helmet: Security headers
- Input Validation: Zod schemas for API requests
-- Every query automatically filtered by tenantId
SELECT * FROM customers WHERE tenantId = ? AND ...
SELECT * FROM orders WHERE tenantId = ? AND ...
SELECT * FROM segments WHERE tenantId = ? AND ...POST /api/auth/login- User loginPOST /api/auth/signup- User registrationPOST /api/auth/logout- User logoutGET /api/auth/me- Current user info
GET /auth- Start OAuth flowGET /auth/callback- OAuth callbackGET /auth/install- App installation
GET /api/v1/tenants/me- Current tenant infoGET /api/v1/tenants/me/stats- Dashboard statisticsPOST /api/v1/tenants/me/sync- Trigger data syncGET /api/v1/tenants/me/sync-status- Recent sync jobsGET /api/v1/tenants/me/sync/:syncRunId/status- Real-time sync progressGET /api/v1/tenants/me/sync/active- Active syncs
GET /api/v1/customers- List customers with filtersGET /api/v1/customers/:id- Customer detailsGET /api/v1/customers/:id/timeline- Customer activity timeline
GET /api/v1/orders- List orders with filtersGET /api/v1/orders/:id- Order details
GET /api/v1/segments- List segmentsPOST /api/v1/segments- Create segmentGET /api/v1/segments/:id- Segment detailsPUT /api/v1/segments/:id- Update segmentDELETE /api/v1/segments/:id- Delete segmentGET /api/v1/segments/:id/members- Segment membersPOST /api/v1/segments/:id/refresh- Refresh segment
GET /api/v1/analytics/rfm- RFM distributionGET /api/v1/analytics/cohorts- Cohort analysisGET /api/v1/analytics/churn- Churn prediction
POST /webhooks/customers/create- Customer createdPOST /webhooks/customers/update- Customer updatedPOST /webhooks/orders/create- Order createdPOST /webhooks/orders/updated- Order updated
sync:subscribe- Subscribe to sync progresssync:unsubscribe- Unsubscribe from syncsync:status- Request current status
sync:active- List of active syncs on connectsync:progress- Progress updatesync:update- Tenant-wide sync notificationsync:completed- Sync finished successfullysync:failed- Sync failedsync:error- Error message
Real-time metrics, revenue trends, and customer insights
Customer segmentation based on Recency, Frequency, and Monetary value
Detailed customer view with purchase history and timeline
Visual rule builder for creating dynamic customer segments
Live progress tracking during Shopify data synchronization
Cohort analysis, churn prediction, and lifetime value metrics
| Command | Description |
|---|---|
pnpm dev |
Start all services in dev mode |
pnpm dev:server |
Start backend API only |
pnpm dev:worker |
Start background worker only |
pnpm dev:client |
Start frontend only |
pnpm build |
Build both frontend and backend |
pnpm build:server |
Build backend only |
pnpm build:client |
Build frontend only |
pnpm start |
Start production servers |
pnpm lint |
Run ESLint on all files |
pnpm typecheck |
Run TypeScript type checking |
pnpm prisma:generate |
Generate Prisma client |
pnpm prisma:migrate |
Run database migrations |
pnpm prisma:studio |
Open Prisma Studio |
pnpm db:seed |
Seed database with sample data |
pnpm test |
Run test suite |
pnpm test:watch |
Run tests in watch mode |
| Service | URL | Status |
|---|---|---|
| Frontend | xsight-frontend-production.up.railway.app | ✅ Live |
| Backend API | xsight-production.up.railway.app | ✅ Live |
| Health Check | /health | ✅ Healthy |
Railway deployment with PostgreSQL, Redis (Upstash), and Shopify integration
- Domain name with SSL certificate (optional, Railway provides free domains)
- PostgreSQL database (Railway, Supabase, or Neon recommended)
- Redis instance (Upstash recommended)
- Shopify Partner account with app created
-
Create Railway Project
railway init
-
Add PostgreSQL Service
- Click "New Service" → "Database" → "PostgreSQL"
- Railway will provide
DATABASE_URLautomatically
-
Add Redis Service
- Use Upstash Redis (recommended)
- Or add Redis plugin in Railway
- Copy
REDIS_URLto environment variables
-
Configure Environment Variables
DATABASE_URL=${{Postgres.DATABASE_URL}} REDIS_URL=<your-upstash-redis-url> SHOPIFY_API_KEY=<from-partner-dashboard> SHOPIFY_API_SECRET=<from-partner-dashboard> SHOPIFY_APP_URL=https://your-backend-domain.railway.app JWT_SECRET=<generated-secret> ENCRYPTION_KEY=<generated-key> FRONTEND_URL=https://your-frontend-domain.vercel.app NODE_ENV=production
-
Deploy
railway up
-
Run Migrations
railway run pnpm prisma migrate deploy
-
Import Repository
- Go to Vercel Dashboard
- Import your Git repository
- Select "Next.js" as framework preset
-
Configure Build Settings
- Build Command:
pnpm build:client - Output Directory:
.next - Install Command:
pnpm install - Root Directory: Leave blank
- Build Command:
-
Environment Variables
NEXT_PUBLIC_API_URL=https://your-backend-domain.railway.app NEXT_PUBLIC_SHOPIFY_API_KEY=<from-partner-dashboard> NODE_ENV=production
-
Deploy
- Click "Deploy"
- Vercel will build and deploy automatically
-
Update App URLs in Partner Dashboard
- App URL:
https://your-backend-domain.railway.app - Allowed redirection URL(s):
https://your-backend-domain.railway.app/auth/callbackhttps://your-frontend-domain.vercel.app
- App URL:
-
Configure API Scopes
read_customers,read_orders,read_products,read_content,read_themes -
Set Webhook URLs
- Customers Create:
https://your-backend-domain.railway.app/webhooks/customers/create - Customers Update:
https://your-backend-domain.railway.app/webhooks/customers/update - Orders Create:
https://your-backend-domain.railway.app/webhooks/orders/create - Orders Update:
https://your-backend-domain.railway.app/webhooks/orders/updated
- Customers Create:
-
GDPR Webhooks
- Customers Data Request:
https://your-backend-domain.railway.app/webhooks/customers/data_request - Customers Redact:
https://your-backend-domain.railway.app/webhooks/customers/redact - Shop Redact:
https://your-backend-domain.railway.app/webhooks/shop/redact
- Customers Data Request:
- Render: Similar to Railway, good PostgreSQL support
- Fly.io: Good for global deployment, built-in Redis
- AWS EC2: Full control, requires more setup
- Netlify: Alternative to Vercel, similar features
- Cloudflare Pages: Fast edge deployment
- AWS Amplify: Integrated with AWS services
- Backend health check responds:
GET /health - Frontend loads without errors
- Shopify OAuth flow completes successfully
- Database migrations applied
- Redis connection working (check worker logs)
- WebSocket connections establish properly
- Webhooks receive and process events
- SSL certificates valid on all domains
- Environment variables set correctly
- Logs configured (Sentry recommended)
Problem: Frontend shows "WebSocket disconnected"
Solutions:
- Check
FRONTEND_URLincludes correct origin - Ensure cookies are sent with
credentials: 'include' - Verify JWT_SECRET matches between services
- Check CORS configuration in
server/index.ts
Problem: Sync jobs don't complete
Solutions:
- Check worker is running:
pnpm dev:worker - Verify Redis connection:
redis-cli ping - Check BullMQ dashboard:
http://localhost:3000/admin/queues - Review worker logs for errors
Problem: Prisma.PrismaClientInitializationError
Solutions:
- Verify
DATABASE_URLformat - Check PostgreSQL is running
- Ensure migrations applied:
pnpm prisma migrate deploy - Test connection:
pnpm prisma db push --skip-generate
Problem: "Invalid redirect_uri" or "Invalid HMAC"
Solutions:
- Update redirect URLs in Partner Dashboard
- Verify
SHOPIFY_APP_URLmatches dashboard - Check
SHOPIFY_API_SECRETis correct - Ensure HTTPS in production
Entity-relationship diagram showing data model and relationships
| Table | Purpose | Key Relationships |
|---|---|---|
tenants |
Store information | One-to-many with all other tables |
users |
User accounts | Many-to-one with tenants |
customers |
Shopify customers | Many-to-one with tenants, one-to-many with orders |
orders |
Customer orders | Many-to-one with customers and tenants |
segments |
Customer segments | Many-to-many with customers via segment_members |
rfm_scores |
RFM calculations | One-to-one with customers |
Every table includes tenantId for complete data isolation:
model Customer {
id String @id @default(cuid())
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id])
// ... other fields
@@index([tenantId])
}- Created development store on Shopify Partners
- Added 50+ dummy products across multiple categories
- Generated 100+ test customers with realistic data
- Created 200+ orders with varied dates and amounts
- Shopify OAuth integration with secure token storage
- Admin API integration for customers, orders, products
- Webhook processing for real-time updates
- BullMQ job queue for reliable background processing
- Multi-tenant architecture with complete data isolation
- Incremental sync with cursor-based pagination
- Real-time progress tracking via WebSocket
- Email-based authentication with JWT
- Real-time analytics: customers, orders, revenue
- Date range filtering for all metrics
- Top 5 customers by spend
- RFM segmentation visualization
- Cohort analysis charts
- Churn prediction indicators
- Revenue trends and order analytics
- Customer lifetime value calculations
- Comprehensive README with setup instructions
- Architecture diagram with data flow
- API endpoint documentation
- Database schema visualization
- Deployment guide for Railway
- Security and multi-tenancy documentation
- Real-time WebSocket Updates: Live sync progress with Socket.IO
- Advanced Segmentation: Visual rule builder with complex conditions
- Customer Timeline: Activity feed showing all interactions
- Rate Limiting: Per-tenant API limits with Redis
- Caching Layer: Redis caching for frequently accessed data
- Error Monitoring: Structured logging with Pino (Sentry-ready)
- Type Safety: Full TypeScript coverage front-to-back
- Modern UI: shadcn/ui components with Tailwind CSS
- Responsive Design: Mobile-friendly dashboard
- GSAP Animations: Smooth page transitions and interactions
| Limitation | Reason | Future Solution |
|---|---|---|
| Single region deployment | Cost optimization for demo | Multi-region with edge caching |
| Manual segment refresh | Simplicity | Automatic refresh via cron jobs |
| Basic error handling | Time constraints | Retry logic with exponential backoff |
| Limited test coverage | Prioritized features | Full unit + integration test suite |
| No email notifications | External dependency | SendGrid/Postmark integration |
-
Monitoring & Observability
- Full Sentry error tracking
- DataDog/New Relic APM
- Custom dashboards for ops metrics
-
Performance Optimization
- Database query optimization with indexes
- Materialized views for analytics
- CDN for static assets
- Redis cluster for high availability
-
Feature Enhancements
- Email campaign builder
- SMS notifications via Twilio
- Product recommendation engine
- A/B testing framework
- Custom report builder
-
Enterprise Features
- SSO/SAML authentication
- Role-based access control (RBAC)
- Audit logs for compliance
- Data export (CSV, PDF)
- White-label customization
-
Testing & Quality
- Unit tests (Jest)
- Integration tests (Supertest)
- E2E tests (Playwright)
- Load testing (k6)
- Security audit (OWASP)
- App Router: Modern routing with server components
- SSR: Better SEO and initial load performance
- Built-in API: Simpler deployment without separate hosting
- TypeScript: Native support without configuration
- Flexibility: Full control over middleware and routing
- Ecosystem: Rich library support for Shopify, Redis, etc.
- WebSocket: Easy Socket.IO integration
- Familiarity: Industry standard for Node.js backends
- Type Safety: Generated types from schema
- Migrations: Automatic migration generation
- Multi-tenancy: Easy filtering by tenantId
- Developer Experience: Excellent autocomplete and errors
- Reliability: Redis-backed persistence
- Retry Logic: Automatic retries with exponential backoff
- Concurrency: Process multiple jobs in parallel
- Monitoring: Built-in dashboard for job inspection
- Speed: Sub-millisecond latency for caching
- Pub/Sub: Real-time progress broadcasting
- Rate Limiting: Token bucket algorithm
- Session Store: Fast session lookups
- API Documentation: Comprehensive API reference
- Development Issues: Lessons learned and solutions
- Design Decisions: Architecture choices and rationale
- Task Requirements: Original internship assignment
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE.md file for details.
[Your Name]
- GitHub: @Nimboo3
- LinkedIn: Your LinkedIn
- Email: your.email@example.com
Built for Xeno FDE Internship Assignment 2025
- Xeno Team: For the challenging and realistic assignment
- Shopify: Excellent API documentation and developer tools
- Next.js Team: Outstanding framework and DX
- Prisma Team: Best ORM for TypeScript
- shadcn/ui: Beautiful accessible components
- Open Source Community: For the amazing tools and libraries
If you have questions about this project:
- Check the documentation
- Review common issues
- Open an issue on GitHub
- Contact me directly
- ✅ Shopify development store with test data
- ✅ Data ingestion service (customers, orders, products)
- ✅ Multi-tenant architecture with data isolation
- ✅ PostgreSQL database with Prisma ORM
- ✅ Insights dashboard with authentication
- ✅ Total customers, orders, revenue metrics
- ✅ Orders by date with filtering
- ✅ Top 5 customers by spend
- ✅ Additional metrics and trends
- ✅ Deployed to Railway + Railway
- ✅ Scheduler for data sync (cron jobs)
- ✅ Webhooks for real-time updates
- ✅ Comprehensive documentation (README + docs/)
- ✅ Architecture diagram
- ✅ API and data model documentation
- ✅ Next steps for productionization
- ✅ Real-time WebSocket progress tracking
- ✅ Advanced RFM segmentation
- ✅ Custom segment builder
- ✅ Redis caching and rate limiting
- ✅ Full TypeScript coverage
- ✅ Modern UI with animations
- ✅ Cohort analysis
- ✅ Churn prediction
- ✅ Public GitHub repository
- ✅ Clean, well-structured code
- ✅ README with setup instructions
- ✅ Architecture diagram
- ✅ API documentation
- ✅ Database schema
- ✅ Known limitations and assumptions
- ⏳ Demo video (7 minutes)
This project is licensed under the MIT License - see the LICENSE.md file for details.
