Skip to content

Conversation

@viniarruda
Copy link
Member

@viniarruda viniarruda commented Dec 31, 2025

🚀 feat: Complete authentication system, absolute paths, and comprehensive documentation

📋 Summary

This PR establishes the foundational infrastructure for the React Ecommerce boilerplate, including a complete authentication system with automatic token refresh, absolute path configuration across the monorepo, Poppins font integration, and extensive documentation for both web and admin apps.


✨ Features

🔐 Authentication System

Token Management

  • ✅ Automatic access token storage on login/register
  • ✅ Automatic refresh token storage
  • ✅ Dual storage strategy (localStorage + memory for SSR support)

Auto Token Refresh

  • ✅ Automatic token refresh on 401 errors
  • ✅ Request queuing during refresh (prevents race conditions)
  • ✅ Automatic retry of failed requests after token refresh
  • ✅ Graceful fallback: redirects to /login if refresh fails
  • ✅ Backend-validated tokens (removed unnecessary client-side checks)

Implementation

// Simplified flow
Request (401)  Get Refresh Token  POST /api/auth/refresh 
 Save New Tokens  Retry Original Request  Resume Queued Requests

📁 Absolute Paths Configuration

SDK Package (@react-shop/sdk)

  • ✅ Changed internal alias from @/ to @sdk/ to avoid conflicts
  • ✅ Added path mappings: @sdk/*, @entities/*, @providers/*, @services/*
  • ✅ Updated all SDK files to use new aliases

Web App

  • ✅ Configured tsconfig.json with absolute paths
  • ✅ Configured next.config.js with webpack aliases
  • ✅ Added mappings for @lib, @entities, @providers, @services, @sdk

Benefits

// ❌ Before
import { setToken } from '../../../client';
import { User } from '../../../../entities/User';

// ✅ After
import { setToken } from '@sdk/client';
import { User } from '@entities/User';

🎨 Typography

Poppins Font Integration

  • ✅ Integrated using Next.js next/font/google for optimal performance
  • ✅ Weights: 300, 400, 500, 600, 700
  • ✅ Applied to both font-sans and font-heading in Tailwind config
  • ✅ Zero layout shift with display: swap
  • ✅ CSS variable support: --font-poppins

📚 Documentation

New Documentation Files

  1. apps/web/FEATURES.md (266 lines)

    • Complete customer-facing store feature list
    • Organized by: Public Pages, Shopping Experience, User Account, UI/UX, Technical
    • 8-week implementation roadmap with 5 phases
    • Priority-based task organization
  2. apps/admin/FEATURES.md (357 lines)

    • Complete admin dashboard feature list
    • Organized by: Dashboard, Product Management, Orders, Customers, Financial, Settings
    • 8-week implementation roadmap with 6 phases
    • Technical requirements for admin-specific patterns
  3. apps/APPS_ARCHITECTURE.md (444 lines)

    • Comprehensive architecture guide
    • Explains web vs admin app separation
    • Data flow diagrams
    • Authentication strategies
    • Deployment options
    • Development workflow
  4. packages/sdk/AUTH_FLOW.md (342 lines)

    • Complete authentication flow documentation
    • Token lifecycle diagram
    • Usage examples for all auth hooks
    • Backend requirements
    • Security best practices
    • Troubleshooting guide
  5. QUICK_START.md (269 lines)

    • Developer quick reference
    • Setup instructions
    • Common commands
    • Test credentials
    • Code examples
    • Troubleshooting tips
  6. IMPLEMENTATION_SUMMARY.md (163 lines)

    • Recent updates summary
    • Technical implementation details
    • What's working checklist
    • Next steps
  7. ABSOLUTE_PATHS_GUIDE.md (updated)

    • Added @sdk alias documentation
    • Updated examples with new paths

🔧 Technical Changes

Modified Files

SDK (packages/sdk/)

src/client.ts                              - Token refresh logic + storage helpers
src/services/mutations/auth/useLogin/      - Save both tokens
src/services/mutations/auth/useRegister/   - Save both tokens  
src/services/mutations/auth/useLogout/     - Updated imports
src/services/queries/products/             - Updated imports
src/providers/ApiProvider.tsx              - Config validation
tsconfig.json                              - Changed @/ to @sdk/

Web App (apps/web/)

app/layout.tsx                             - Poppins font + apiConfig fix
tsconfig.json                              - Absolute path mappings
next.config.js                             - Webpack aliases
FEATURES.md                                - Complete rewrite

Design System (packages/design-system/)

src/styles/global.css                      - Removed redundant font-family
tailwind.config.ts                         - Updated font config to use Poppins

Documentation

apps/admin/FEATURES.md                     - New file
apps/APPS_ARCHITECTURE.md                  - New file
packages/sdk/AUTH_FLOW.md                  - New file
QUICK_START.md                             - New file
IMPLEMENTATION_SUMMARY.md                  - New file
ABSOLUTE_PATHS_GUIDE.md                    - Updated

🎯 Key Decisions

1. Admin as Separate App

Decision: Admin dashboard is a separate Next.js app (apps/admin), not a route in web app.

Reasons:

  • 🔒 Security: Admin code doesn't ship to customers
  • 📦 Performance: Smaller bundle size for customer store
  • 🎨 Different UI/UX needs
  • 🚀 Independent deployments
  • 🔐 Separate RBAC system

2. Backend Token Validation

Decision: Removed client-side refresh token validation, let backend handle it.

Benefits:

  • Backend is single source of truth
  • Simpler client logic
  • More flexible validation rules
  • Better error messages from backend

3. Absolute Paths Strategy

Decision: Use @sdk/ prefix instead of @/ for SDK package.

Reasons:

  • Avoids conflicts with web app's @/ alias
  • Clearer import origins
  • Better IDE autocomplete
  • Consistent across monorepo

🧪 Testing Checklist

  • Token refresh works automatically on 401
  • Multiple requests queue correctly during refresh
  • Failed refresh redirects to login
  • Poppins font loads and applies correctly
  • Absolute imports resolve in web app
  • Absolute imports resolve in SDK
  • Dev server starts without errors
  • All documentation is accurate

📊 Impact

Performance

  • ✅ Automatic token refresh reduces failed requests
  • ✅ Request queuing prevents duplicate refresh calls
  • ✅ Poppins font optimized via Next.js

Developer Experience

  • ✅ Absolute imports improve code readability
  • ✅ Comprehensive docs reduce onboarding time
  • ✅ Clear architecture guide prevents confusion
  • ✅ Quick start guide speeds up setup

Maintainability

  • ✅ Centralized token management
  • ✅ Type-safe SDK with React Query
  • ✅ Well-documented feature roadmaps
  • ✅ Clear separation of concerns (web vs admin)

🚀 What's Ready

  1. Authentication - Complete JWT flow with auto-refresh
  2. Token Storage - Persistent + memory storage
  3. Absolute Paths - Configured across monorepo
  4. Typography - Poppins font integrated
  5. Documentation - Comprehensive guides for all aspects
  6. Architecture - Clear app separation strategy
  7. Feature Roadmaps - 8-week plans for web & admin

📋 Next Steps (Follow-up PRs)

Phase 1: Foundation

  • Setup admin app structure
  • Create authentication pages (login, register)
  • Build layout components (header, footer, navigation)

Phase 2: Web App - Core Shopping

  • Home page with featured products
  • Product listing page with filters
  • Product detail page
  • Shopping cart functionality

Phase 3: Admin App - Product Management

  • Product CRUD interface
  • Category management
  • Image upload
  • Stock management

📝 Breaking Changes

None. This is foundational work that doesn't affect existing functionality.


📸 Screenshots

Poppins Font Applied

✅ Font loads correctly in browser with proper weights

Dev Server Running

http://localhost:3001 - Web app running without errors
✅ All absolute imports resolved
✅ Hot reload working


👥 Review Notes

For Reviewers

Focus Areas:

  1. Token refresh logic in packages/sdk/src/client.ts
  2. Absolute path configurations in tsconfig.json files
  3. Documentation accuracy and completeness
  4. Architecture decisions in APPS_ARCHITECTURE.md

Testing:

  1. Start dev server: pnpm dev
  2. Check browser console for errors
  3. Verify font loads: inspect element to see Poppins
  4. Test imports: all @sdk/*, @entities/* should resolve

✅ Checklist

  • Code follows project conventions
  • All tests pass (SDK and web app)
  • Documentation is complete and accurate
  • No console errors in dev mode
  • Absolute imports work correctly
  • Token refresh tested manually
  • Poppins font verified in browser
  • Commit messages follow conventional commits
  • All changes committed and pushed

📞 Questions?

  • Auth Flow: See packages/sdk/AUTH_FLOW.md
  • Architecture: See apps/APPS_ARCHITECTURE.md
  • Getting Started: See QUICK_START.md
  • Web Features: See apps/web/FEATURES.md
  • Admin Features: See apps/admin/FEATURES.md

Ready to merge and start building features! 🎉

- Remove GraphQL dependencies and code generation
- Create entity types for all models
- Restructure to queries/ and mutations/ folders
- Implement REST API hooks with React Query
- Update providers for REST client
- Update IMPLEMENTATION_STATUS.md with current progress
- Configure Storybook 8.0 with React and Vite
- Add responsive breakpoints (sm, md, lg, xl, 2xl) to panda.config
- Enhance Input component with variants and sizes
- Create Select component with size variants
- Create Icon component with lucide-react
- Create Modal component with overlay and sizes
- Create Toast component with variants (success, error, warning, info)
- Create Skeleton component with text/circular/rectangular variants
- Create Divider component with horizontal/vertical orientation
- Create Avatar component with image, initials, and fallback
- Update component exports and organization
- Add lucide-react for icon system
- Typography components (Heading, Text) already exist
- Button component already enhanced
- Badge component already exists
- ProductCard components already exist
- Organize components into Atoms/Molecules/Organisms folders
- Extract colors and spacing tokens into separate files
- Import tokens in panda.config.ts for better maintainability
- Update component exports to reflect new structure

Atomic Design Structure:
- Atoms: Icon, Input, Button, Badge, Avatar, Divider, Skeleton, Text, Heading, Layout components
- Molecules: Select, PriceDisplay, Rating, Toast
- Organisms: Modal, ProductCard
- Split each hook into separate folders with dedicated files
- Add types.ts for input/output type definitions
- Add key.ts for React Query keys
- Add request.ts for API request logic
- Add index.ts for hook implementation

Structure:
- queries/auth/useMe/
- mutations/auth/useLogin/
- mutations/auth/useRegister/
- mutations/auth/useLogout/

Benefits:
- Better separation of concerns
- Easier to test individual parts
- More maintainable codebase
- Clearer dependencies
- Add route constants in SDK (AUTH_ROUTES, PRODUCT_ROUTES, etc.)
- Configure tsconfig path aliases for all packages
- Update SDK auth hooks to use absolute imports
- Remove relative imports (../../) in favor of @Aliases
- Add comprehensive documentation (ABSOLUTE_PATHS_GUIDE.md)

Path aliases configured:
- SDK: @Entities, @providers, @services
- Design System: @Atoms, @molecules, @organisms, @theme
- Web App: @components, @app, @lib, @hooks, @utils
- Server: @user, @auth, @Product, @cart, etc.

Benefits:
- Cleaner, more maintainable imports
- Centralized API route management
- Easier refactoring and file moves
- Better IDE support and auto-completion
- Remove duplicate route entries (CREATE, UPDATE, DELETE)
- Use HTTP methods (GET, POST, PUT, DELETE) instead of separate constants
- Change to lowercase camelCase naming (list, detail, base)
- Consolidate routes using same URL

Before:
  PRODUCT_ROUTES = {
    LIST: '/api/products',
    CREATE: '/api/products',
    UPDATE: (id) => '/api/products/${id}',
    DELETE: (id) => '/api/products/${id}',
  }

After:
  PRODUCT_ROUTES = {
    list: '/api/products',
    detail: (id) => '/api/products/${id}',
  }

Updated all route constants:
- AUTH_ROUTES: login, register, logout, me
- PRODUCT_ROUTES: list, detail
- CATEGORY_ROUTES: list, detail
- CART_ROUTES: base, items, item, clear
- ORDER_ROUTES: list, detail, status, cancel, all
- REVIEW_ROUTES: list, base, detail, moderate
- Update to Next.js 14.2+ and React 19
- Add SDK and Design System dependencies
- Configure Next.js with package transpilation
- Create App Router structure (src/app)
- Add root layout with SdkProvider
- Create home page with:
  - Hero section
  - Product list (SDK integration test)
  - Design System components showcase
  - Loading states with Skeleton
  - Error handling
- Configure absolute paths in tsconfig
- Add PostCSS config for PandaCSS
- Create comprehensive documentation:
  - FEATURES_WEB.md (complete feature roadmap)
  - README.md (setup and development guide)
  - ENV_SETUP.md (environment variables)

Dependencies added:
- next@14.2.0, react@19.0.0, react-dom@19.0.0
- react-hook-form, zod, @hookform/resolvers
- @react-shop/sdk, @react-shop/design-system

Next steps:
- Install dependencies
- Start backend server
- Test home page with real API data
- Move from src/app to app/ (Next.js 14 convention)
- Update tsconfig paths to remove src/
- Fix React.Node to React.ReactNode type
- Update documentation to reflect correct structure

Next.js 14 structure:
apps/web/
├── app/           # Next.js App Router (NOT src/app)
├── components/
├── lib/
├── hooks/
└── public/
- Ignore .next/ build output
- Ignore node_modules and dependencies
- Ignore environment files
- Ignore TypeScript build info
- Move global.css to Design System (src/styles/global.css)
- Import global.css from DS in web app layout
- Add @styled-system path alias in tsconfig
- Update Badge and Button components to use @styled-system imports
- Define inline CVA recipes for components
- Include styled-system in tsconfig
- Add comprehensive PANDACSS_SETUP.md guide

Changes per PandaCSS docs:
- Use @styled-system/* for all PandaCSS imports
- Generate styled-system via 'panda codegen'
- Import global CSS with layers in app
- Use CVA for component variants

Next steps:
1. Run 'pnpm install' in root
2. Run 'cd packages/design-system && pnpm prepare'
3. This generates the styled-system directory
4. All components will have type-safe styling

Reference: https://panda-css.com/docs/installation/nextjs
Updated all components (20+ files) to fix import errors:

Atoms:
- Avatar, Badge, Box, Button: Use @styled-system/jsx and @styled-system/css
- Card: Inline CVA recipe with variants (elevated, outline, filled)
- Container, Flex, Grid, Stack: Simple styled components
- Divider: Horizontal/vertical orientation
- Heading, Text: Typography with size/weight props
- Icon: Lucide integration with size/color variants
- Input: Form input with variants (outline, filled) and validation states
- Skeleton: Loading states (text, circular, rectangular)

Molecules:
- Select: Custom select with chevron icon
- Toast: Notification with variants (success, error, warning, info)
- PriceDisplay: Currency formatting with original price strikethrough
- Rating: Star rating display

Organisms:
- Modal: Dialog with overlay, sizes, and keyboard controls
- ProductCard: Complete product card with image, price, rating, discount badge

All components now:
- ✅ Use @styled-system/* imports (no relative paths)
- ✅ Define inline CVA recipes
- ✅ Have proper TypeScript types
- ✅ Support variants and sizes
- ✅ Work with PandaCSS generated styles

No more import errors after running 'panda codegen'!
Phase 1: Setup & Basic Components

Dependencies:
- ✅ Remove @pandacss/dev
- ✅ Add tailwindcss, autoprefixer, postcss
- ✅ Add tailwind-merge, tailwind-variants, clsx

Configuration:
- ✅ Create tailwind.config.ts for DS and web app
- ✅ Update postcss.config.js
- ✅ Update global.css with Tailwind directives
- ✅ Create cn() utility function

Migrated Components (7/20):
- ✅ Box, Container, Flex, Grid, Stack (layout)
- ✅ Button (with tailwind-variants)
- ✅ Badge (with tailwind-variants)

Benefits:
- More beginner-friendly
- Better community support
- Intuitive class names
- Excellent VS Code integration
- Industry standard

Next: Migrate remaining 13 components
Migrated all 20 components from PandaCSS to Tailwind
Added tailwind-variants for component variants
Updated all documentation and configs
Removed PandaCSS dependencies and files
Changed all component imports from @lib/utils to ../../../lib/utils
to fix module resolution in Next.js web app
Added webpack configuration to Next.js to resolve absolute paths:
- @lib -> Design System lib folder
- @Entities, @providers, @services -> SDK folders

Updated tsconfig.json with path mappings
Reverted all components to use @lib/utils imports
Changed SDK internal imports from @/ to @SDK to avoid conflicts
Added @SDK alias to webpack and tsconfig
Updated all SDK files using @/client to use @sdk/client
Updated @/entities to @entities/Product
- Fixed layout.tsx to pass apiConfig object instead of apiUrl string
- Added validation in ApiProvider for config object
- Changed useMemo dependency to use full config object
- Added setRefreshToken and getStoredRefreshToken helpers
- Implemented automatic token refresh on 401 errors
- Added request queue to handle multiple failed requests during refresh
- Updated useLogin and useRegister to save both access and refresh tokens
- Integrated Poppins font from Google Fonts with weights 300-700
- Updated Tailwind config to use Poppins as default font family
- Backend is responsible for token validation
- Removed client-side refresh token check
- Simplified token refresh flow
- Fixed CSS syntax in global.css
- Updated apps/web/FEATURES.md with detailed customer-facing features
- Created apps/admin/FEATURES.md with admin dashboard features
- Created apps/APPS_ARCHITECTURE.md explaining app relationships
- Organized features by priority and implementation phases
- Clarified that admin is a separate app, not a URL in web
@viniarruda viniarruda merged commit 5e35a11 into main Dec 31, 2025
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants