π Production Ready! A unified e-commerce platform for footwear with customer storefront and admin portal in one application.
Status: β All features implemented and working Architecture: Single-app with role-based access control Last Updated: October 26, 2025
- Quick Start
- Admin Portal Access Issues
- Architecture
- Features
- Database Schema
- Getting Started
- Application Routes
- Access Control
- Admin Navigation
- Interactive Product Cards
- Address Management
- Deployment
- Troubleshooting
- Customization
npm run devVisit: http://localhost:3000
# Sign up first at http://localhost:3000/auth/signup
# Then run this command with your email:
node make-admin.js your@email.comAlternative Method (Manual):
- Go to your Supabase Dashboard
- Table Editor β profiles β Find your user β Set role to
admin - Sign out and sign in again
Visit: http://localhost:3000/admin
This is a common issue. Here's how to fix it:
# After signing up, run:
node make-admin.js your@email.comThe script will:
- β Find your user in the database
- β Check current role
- β Promote to admin
- β Confirm success
- Open Supabase SQL Editor
- Run this query:
UPDATE profiles
SET role = 'admin'
WHERE email = 'your@email.com';-- Verify user profile exists
SELECT id, email, role FROM profiles WHERE email = 'your@email.com';If no results: The user hasn't signed up or profile wasn't created.
Run this in Supabase SQL Editor to check if tables exist:
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;Should show: profiles, products, orders, etc.
If tables don't exist, run the migration:
- File:
packages/database/supabase/migrations/20241026000001_create_improved_ecommerce_schema.sql - Copy entire contents and run in Supabase SQL Editor
Open browser console (F12) when trying to access /admin:
Expected Console Output (Success):
[useAdminAuth] Starting admin access check...
[useAdminAuth] User: Found (your@email.com)
[useAdminAuth] Profile: Found (role: admin)
[useAdminAuth] Is admin: true
[useAdminAuth] Admin check complete. Admin: true
If you see:
User: Noneβ Not signed in (go to/auth/signin)Profile: Noneβ Profile wasn't created (database issue)role: customerβ Need to promote to admin (use make-admin.js)Is admin: falseβ Role check failed (verify role is 'admin' or 'super_admin')
- Not signing out after promotion β Always sign out and sign back in
- Wrong email β Double-check email matches exactly
- Database not migrated β Run the migration first
- Browser cache β Clear cache and hard reload (Ctrl+Shift+R)
β¨ Unified Single-App Architecture - One Next.js application serving both customer and admin features with intelligent role-based routing.
project/
βββ apps/client/ # π MAIN APP (Port 3000)
β βββ app/
β β βββ / # Customer: Landing page
β β βββ /products # Customer: Product catalog
β β βββ /cart # Customer: Shopping cart
β β βββ /checkout # Customer: Checkout
β β βββ /account # Customer: Account pages
β β βββ /auth # Public: Sign in/up
β β βββ /admin # π Admin: Management portal
β β βββ layout.tsx # β¨ Auto-auth wrapper
β β βββ page.tsx # Dashboard
β β βββ products/ # Product management
β β βββ orders/ # Order management
β β βββ customers/ # Customer management
β β βββ categories/ # Category management
β β βββ promo-codes/ # Promo codes
β β βββ analytics/ # Analytics
β βββ components/
β βββ layout/ # Customer UI
β βββ admin/ # Admin UI
β β βββ AdminLayout.tsx # Layout wrapper
β β βββ AdminSidebar.tsx # Navigation sidebar
β β βββ AdminBreadcrumb.tsx # Breadcrumb navigation
β βββ blocks/ # Reusable sections
βββ packages/
β βββ database/ # Supabase client & types
β βββ shared-lib/ # Business logic & APIs
β βββ shared-ui/ # Reusable UI components
βββ make-admin.js # π Admin creation utility
Benefits: β Single deployment β’ β Shared authentication β’ β Cost effective β’ β Better UX
- Landing Page - Beautiful homepage with featured products
- Product Catalog - Browse with search, filters, and pagination
- Product Details - Full pages with variants, images, descriptions
- Shopping Cart - Persistent cart with guest support
- User Authentication - Secure sign up/sign in with Supabase
- Account Management - Profile, order history, addresses
- Checkout Flow - Ready for payment integration
- Responsive Design - Mobile-first across all devices
- Interactive Product Cards - 3D tilt effect premium showcase
- Dashboard - Real-time stats and analytics overview
- Product Management - Full CRUD operations with media support
- Order Management - View and process customer orders
- Customer Management - View profiles and order history
- Category Management - Organize products into categories
- Inventory Tracking - Low stock alerts and reservations
- Promo Codes - Discount code management
- Analytics - Product performance and sales metrics
- Preview Cards - Interactive product card builder
- Mobile Responsive - Drawer sidebar, touch-friendly
- Monorepo Setup - npm workspaces for code sharing
- Scalable Database - 14 tables with ENUMs, indexes, full-text search
- Row Level Security - Comprehensive RLS policies
- Type Safety - Full TypeScript implementation
- Shared Packages - Reusable components and utilities
- Authentication - Role-based access control
- Admin Auth Hook - Consistent admin authentication
- Centralized Navigation - Single source of truth
- Error Handling - Beautiful error pages
- profiles - User accounts with roles ('customer', 'admin', 'super_admin')
- categories - Product categories with hierarchy
- products - Main catalog with full-text search
- product_images - Multiple images per product
- product_variants - Size, color, inventory management
- product_reviews - Customer reviews and ratings
- addresses - Customer shipping/billing addresses
- carts - Shopping cart management
- cart_items - Items in shopping carts
- orders - Customer order records
- order_items - Line items for orders
- promo_codes - Discount code management
- order_status_history - Order tracking
- inventory_reservations - Concurrent checkout handling
- β ENUMs for type safety and performance
- β Composite indexes for complex queries
- β Full-text search indexes (GIN)
- β Inventory reservations (prevents overselling)
- β
Soft deletes with
archived_at - β Audit trails and analytics views
- customer - Default role for all new users
- admin - Full admin access to all features
- super_admin - Reserved for future enhanced permissions
- Node.js 18+ installed
- Supabase account and project
- npm (comes with Node.js)
- Install dependencies:
cd "project 4"
npm install-
Environment variables are already configured in:
apps/client/.env.local(main app)
-
Set up the database:
- Go to Supabase SQL Editor
- Run:
packages/database/supabase/migrations/20241026000001_create_improved_ecommerce_schema.sql - This creates all 14 tables with proper indexes and policies
-
Create your first admin user:
# Sign up at http://localhost:3000/auth/signup first
# Then run:
node make-admin.js your@email.com- Start the application:
npm run devVisit http://localhost:3000
# Start the unified app (recommended)
npm run dev # Port 3000 - Everything in one app
# Build commands
npm run build # Build for production
npm run start # Start production server
# Quality checks
npm run lint # Check code quality
npm run typecheck # Check TypeScript
npm run clean # Clean build artifacts| Route | Description |
|---|---|
/ |
Landing page with featured products |
/products |
Product catalog |
/products/[slug] |
Individual product page |
/auth/signin |
Sign in page |
/auth/signup |
Sign up page |
/demo/interactive-card |
Interactive card demo |
| Route | Description |
|---|---|
/cart |
Shopping cart |
/checkout |
Checkout flow |
/account/profile |
User profile (editable) |
/account/orders |
Order history |
/account/addresses |
Saved addresses |
| Route | Description |
|---|---|
/admin |
Dashboard with real-time stats |
/admin/products |
Manage products (CRUD) |
/admin/orders |
Manage orders |
/admin/customers |
View customers |
/admin/categories |
Manage categories |
/admin/promo-codes |
Manage promo codes |
/admin/analytics |
View analytics |
/admin/preview-cards |
Interactive card builder |
/admin/unauthorized |
Error page for non-admin users |
- User visits
/admin layout.tsxautomatically runsuseAdminAuthhook- Hook checks authentication status
- Hook verifies admin/super_admin role in database
- If not admin β redirects to
/admin/unauthorized - If not authenticated β redirects to
/auth/signin?redirect=/admin - If admin β shows admin content
Method 1: Admin Utility Script (Recommended) β
node make-admin.js user@example.comMethod 2: Supabase Dashboard
- Go to your Supabase project dashboard
- Table Editor β profiles
- Find your user β Set role to
admin - Sign out and sign back in
Method 3: SQL Editor
UPDATE profiles SET role = 'admin' WHERE email = 'your@email.com';Open browser console (F12) when accessing /admin:
[useAdminAuth] Starting admin access check...
[useAdminAuth] User: Found (your@email.com)
[useAdminAuth] Profile: Found (role: admin)
[useAdminAuth] Is admin: true
β
Admin check complete
All admin navigation is configured in one place: apps/client/config/admin-navigation.ts
Navigation Items:
- Dashboard - Overview and statistics
- Products - Product management
- Orders - Order processing
- Customers - Customer database
- Categories - Category organization
- Promo Codes - Discount management
- Analytics - Business insights
- Preview Cards - Card builder tool
- β Automatic Authentication - Layout handles auth for all pages
- β Mobile Responsive - Drawer sidebar on mobile
- β Breadcrumb Navigation - Auto-generated from URL
- β Active State - Highlights current page
- β Loading States - Beautiful skeleton loaders
- β Error Pages - Custom 404 and unauthorized pages
Step 1: Create the page file
// apps/client/app/admin/new-feature/page.tsx
'use client';
export default function NewFeaturePage() {
return (
<div>
<h1 className="text-3xl font-bold">New Feature</h1>
<p>Your content here...</p>
</div>
);
}Step 2: Add to navigation config
// apps/client/config/admin-navigation.ts
import { NewIcon } from 'lucide-react';
export const adminNavigation = [
// ... existing items
{
id: 'new-feature',
name: 'New Feature',
href: '/admin/new-feature',
icon: NewIcon,
description: 'Manage new feature',
},
];That's it! The page is now:
- β Protected by authentication
- β Wrapped in AdminLayout
- β Shows in sidebar
- β Has breadcrumb navigation
- β Mobile responsive
- β¨ 3D Tilt Effect - Follows mouse movement
- π Glassmorphism - Modern semi-transparent design
- π Gradient Overlays - Ensures text readability
- π Smooth Animations - Hardware-accelerated
- π± Responsive - Works on all screen sizes
Quick Integration (Easiest):
import { PremiumShowcase } from "@/components/blocks/PremiumShowcase";
<PremiumShowcase limit={6} theme="dark" />Individual Cards:
import { InteractiveProductCard } from "@/components/ui/card-7";
<InteractiveProductCard
title="Nike M2K Tekno"
description="Elevate Your Every Step"
price="$149"
imageUrl="https://images.unsplash.com/photo-1542291026-7eec264c27ff"
logoUrl="https://upload.wikimedia.org/wikipedia/commons/a/a6/Logo_NIKE.svg"
/>- User Demo: http://localhost:3000/demo/interactive-card
- Admin Builder: http://localhost:3000/admin/preview-cards
| Prop | Type | Required | Description |
|---|---|---|---|
title |
string | Yes | Product name |
description |
string | Yes | Short tagline |
price |
string | Yes | Display price |
imageUrl |
string | Yes | Product image URL |
logoUrl |
string | Yes | Brand logo URL |
className |
string | No | Additional CSS classes |
Status: β Fully Implemented
- β Add New Addresses - Full address form with validation
- β Edit Existing Addresses - Update any saved address
- β Delete Addresses - Remove addresses with confirmation
- β Set Default Address - Mark preferred address
- β Multiple Address Types - Shipping, Billing, or Both
- β Address Cards - Beautiful card display with badges
- β Mobile Responsive - Works perfectly on all devices
- Sign in to your account
- Click your name β "Addresses"
- Or visit: http://localhost:3000/account/addresses
- π Shipping - For deliveries
- π³ Billing - For payments
- π¦ Both - Dual purpose
// Available in @repo/shared-lib
getAddresses(userId) // Get all user addresses
getDefaultAddress(userId) // Get default address
createAddress(userId, data) // Add new address
updateAddress(addressId, data) // Update address
deleteAddress(addressId) // Remove address
setDefaultAddress(userId, addressId) // Set default-
Import project to Vercel:
- Connect your GitHub repo
- Import
apps/clientas root directory - Framework: Next.js
-
Environment Variables:
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key_here SUPABASE_SERVICE_ROLE_KEY=your_service_role_key_here
-
Deploy:
vercel --prod
- Run database migration in Supabase
- Create admin users using SQL or utility script
- Test admin portal access
- Upload product data
- Configure domain settings
Problem: Can't access /admin (redirects to unauthorized)
Solutions:
- Check role in database:
SELECT role FROM profiles WHERE email = 'your@email.com' - Should return:
role = 'admin'or'super_admin' - Use admin utility:
node make-admin.js your@email.com - Clear browser cache and sign in again
- Check console logs for
[useAdminAuth]messages - Verify you signed out and signed back in after role change
Problem: "supabaseKey is required" error
Solution:
- Stop dev server (Ctrl+C)
- Clear cache:
rm -rf apps/client/.next - Verify
.env.localexists inapps/client/ - Restart:
npm run dev
Problem: Tables don't exist
Solution:
- Run migration in Supabase SQL Editor
- File:
packages/database/supabase/migrations/20241026000001_create_improved_ecommerce_schema.sql - Verify tables exist:
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'
Problem: Type errors or import issues
Solutions:
- Clean install:
npm run clean && npm install - Check imports use correct aliases (
@repo/database,@/components) - Ensure all types are synced (role types updated)
- Rebuild:
npm run build
Problem: Build fails or runtime errors
Solutions:
- Check Node.js version (18+ required)
- Delete
node_modulesand reinstall - Clear Next.js cache:
rm -rf apps/client/.next - Check for circular dependencies
- Review error logs carefully
Problem: Users can't sign in or sign up
Solutions:
- Verify Supabase URL and keys are correct
- Check email confirmation settings in Supabase
- Review RLS policies in database
- Clear browser cookies
- Test with different browser/incognito
Recommendation: Implement rate limiting on admin API routes to prevent brute force attacks and abuse.
- upstash/ratelimit - Redis-based rate limiting (recommended for production)
- express-rate-limit - In-memory rate limiting (good for development)
- @vercel/kv - Vercel KV store for rate limiting
// middleware/rateLimit.ts
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, "10 s"), // 10 requests per 10 seconds
});
export async function checkRateLimit(identifier: string) {
const { success, limit, remaining, reset } = await ratelimit.limit(identifier);
if (!success) {
throw new Error("Rate limit exceeded");
}
return { limit, remaining, reset };
}
// Usage in API routes
export async function GET(request: Request) {
try {
const ip = request.headers.get("x-forwarded-for") || "unknown";
await checkRateLimit(`admin_api_${ip}`);
// Your API logic here
} catch (error) {
if (error.message === "Rate limit exceeded") {
return NextResponse.json(
{ error: "Too many requests" },
{ status: 429 }
);
}
// Handle other errors
}
}For development or low-traffic scenarios:
const requestCounts = new Map<string, { count: number; resetTime: number }>();
export function simpleRateLimit(identifier: string, maxRequests: number = 10, windowMs: number = 60000) {
const now = Date.now();
const record = requestCounts.get(identifier);
if (!record || now > record.resetTime) {
requestCounts.set(identifier, { count: 1, resetTime: now + windowMs });
return true;
}
if (record.count >= maxRequests) {
return false;
}
record.count++;
return true;
}- UI Components: Add to
packages/shared-ui/ui/ - API Functions: Add to
packages/shared-lib/api/ - Database Changes: Update migration files in
packages/database/supabase/migrations/ - Admin Pages: Follow the admin page creation guide above
- Uses Tailwind CSS with shadcn/ui components
- Primary colors: Blue (
blue-600,blue-700) - Consistent design system throughout
- Customize in
tailwind.config.ts
# Root level (all workspaces)
npm install <package>
# Specific workspace
npm install <package> -w apps/client
npm install <package> -w packages/databaseCurrent: ShoeHub (Footwear E-Commerce)
To Customize:
- Update logo and name in
Header.tsx - Change navigation items in
admin-navigation.ts - Update database categories
- Modify product descriptions
- Update metadata and SEO
Supabase client configuration and TypeScript types.
Exports:
supabase- Supabase client instancecreateAdminClient()- Admin client with service rolesignUp(),signIn(),signOut()- Auth helpers- All database types (Profile, Product, Order, etc.)
API helpers, utilities, and business logic.
Exports:
- Product API:
getProducts(),getProductBySlug(), etc. - Cart API:
getOrCreateCart(),addToCart(), etc. - Admin APIs: Products, Orders, Customers, Analytics
- Address API: Full address management
cn()- Tailwind utility function
Reusable UI components built with shadcn/ui.
Exports:
- All shadcn/ui components (Button, Card, Dialog, etc.)
useToast()hook- Form components
- Layout primitives
Run in Supabase SQL Editor:
-- See seed-data.sql for complete SQL-- Product performance
SELECT * FROM product_analytics ORDER BY total_revenue DESC;
-- Low stock alerts
SELECT * FROM low_stock_alerts;
-- Recent orders
SELECT * FROM orders ORDER BY created_at DESC LIMIT 10;# Check database connection
node check-database.js
# Verify schema
node verify-schema.js
# Seed database
node seed-database.js- β Database schema deployed to Supabase
- β Admin user created (using make-admin.js)
- β App running on http://localhost:3000
- β Can access admin portal at /admin
- β Can edit user profile at /account/profile
- β Address management working
- β Customer features working (cart, checkout)
- β Admin features working (product management)
- β Interactive cards displaying correctly
- β No TypeScript or linting errors
- Test Everything - Run through the testing checklist
- Create Admin User - Use
make-admin.jsutility - Add Products - Use admin portal to add inventory
- Customize Styling - Update colors and branding
- Deploy - Push to production when ready
- Integrate Payments - Add Stripe or other payment processor
- Add Email - Set up notifications (Resend, SendGrid)
- SEO - Optimize metadata and sitemaps
- This README - Complete guide
- Inline code comments - Implementation details
- Demo pages - Interactive examples
- Console logs - Debugging information
apps/client/app/admin/layout.tsx- Admin authentication wrapperapps/client/hooks/useAdminAuth.ts- Admin auth logicapps/client/config/admin-navigation.ts- Navigation configurationpackages/database/supabase/types.ts- Database typesmake-admin.js- Admin creation utility
node make-admin.js user@example.com- Create file in
apps/client/app/admin/[page-name]/page.tsx - Add navigation item to
config/admin-navigation.ts - Done!
INSERT INTO products (name, slug, description, base_price, is_featured)
VALUES ('Running Shoes', 'running-shoes', 'Comfortable running shoes', 129.99, true);SELECT email, role FROM profiles WHERE email = 'user@example.com';UPDATE profiles SET role = 'admin' WHERE email = 'user@example.com';- Always sign out and sign back in after changing roles
- Use the make-admin.js script instead of manual SQL when possible
- Check browser console for detailed debug logs
- Clear cache if you see stale data
- Test in incognito to verify authentication flows
- Use demo pages to preview components before integration
- Keep database types synced with schema changes
- Backup database before major migrations
- Test on mobile - many users shop on phones
- Monitor RLS policies - they affect performance
- Check this README for common issues
- Review console logs for errors
- Verify database connection
- Test with demo pages first
- Check Supabase dashboard for data
When reporting issues, include:
- Error messages from console
- Steps to reproduce
- Expected vs actual behavior
- Browser and OS information
- Screenshot if applicable
- β Fixed admin authentication issues
- β
Added
make-admin.jsutility script - β Updated types to include super_admin role
- β Enhanced error handling and logging
- β Consolidated documentation
- β Address management system
- β Interactive product cards
- β Admin navigation improvements
- β Mobile responsive design
- β ShoeHub rebranding
- β Initial release
- β Customer storefront
- β Admin portal
- β Database schema
- β Authentication system
Built with: Next.js 13 β’ Supabase β’ TypeScript β’ Tailwind CSS β’ shadcn/ui β’ Radix UI
Ready for production! π
Last Updated: October 26, 2025
Maintainers: Development Team
License: Proprietary