RednGift Frontend Overview
Overview
Section titled “Overview”Purpose
Section titled “Purpose”RednGift is a web platform that simplifies organizing gift exchanges and Secret Santa events. The application enables users to:
- Create and manage gift exchange groups (Secret Santa)
- Build and share wishlists with items they want to receive
- Invite participants via phone number or shareable link
- Automatically perform Secret Santa raffles (matching)
- View matched participant’s wishlists while maintaining anonymity
- Communicate with matched participants via real-time chat
- Browse trending gift items for inspiration
Target users: Individuals organizing gift exchanges for friends, family, or coworkers.
Non-goals:
- Payment processing or e-commerce transactions
- Physical gift delivery or logistics
- Public marketplace for selling items
Architecture
Section titled “Architecture”┌─────────────────────────────────────────────────────────┐│ Next.js App Router ││ ┌────────────┐ ┌───────────┐ ┌──────────────────┐ ││ │ Auth Pages │ │ Home Pages│ │ Invite Pages │ ││ │ /auth/* │ │ /(home)/* │ │ /invite/[slug] │ ││ └────────────┘ └───────────┘ └──────────────────┘ │└─────────────────────────────────────────────────────────┘ │ ┌─────────────────┼─────────────────┐ │ │ │ ┌────▼────┐ ┌─────▼─────┐ ┌─────▼──────┐ │ Redux │ │ Auth │ │ WebSocket │ │ Store │ │ Context │ │ Client │ │ (State) │ │ (JWT) │ │ (Real-time)│ └────┬────┘ └─────┬─────┘ └─────┬──────┘ │ │ │ └─────────────────┼─────────────────┘ │ ┌─────▼──────┐ │ Handlers │ │ (API Layer)│ └─────┬──────┘ │ ┌─────▼──────────┐ │ REST API │ │ redngift-ws │ │ (Backend) │ └────────────────┘Key architectural decisions:
Section titled “Key architectural decisions:”- Server/Client separation: Next.js App Router with ‘use client’ for interactive components
- State persistence: Redux Toolkit with redux-persist for offline resilience
- Real-time updates: WebSocket singleton for chat and notifications
- Authentication: JWT tokens stored in localStorage with automatic session management
- Error tracking: Sentry integration across all layers
Code Layout
Section titled “Code Layout”src/├── app/ # Next.js 13+ App Router pages│ ├── (home)/ # Authenticated routes (layout with AuthGuard)│ ├── auth/ # Authentication pages│ └── invite/ # Public invitation acceptance pages├── auth/ # Authentication logic│ ├── context/ # AuthProvider (JWT) and WebSocketProvider│ └── guard/ # Route guards (AuthGuard, GuestGuard)├── components/ # Reusable UI components├── layouts/ # Page layouts (home, auth, compact)├── sections/ # Feature-specific page sections│ ├── grupo/ # Group management views│ ├── wishlist/ # Wishlist views│ └── mensajes/ # Chat/messaging views├── services/ # API layer│ └── handlers/ # Domain-specific API handlers├── types/ # TypeScript type definitions├── utils/ # Utilities and Redux store│ └── redux/ # Redux slices and store configuration├── theme/ # Material-UI theme customization└── routes/ # Route path definitions and hooksBuild, Test, Lint Commands
Section titled “Build, Test, Lint Commands”# Developmentyarn dev # Start dev server on port 8083yarn dev:ts # Dev server + TypeScript watch mode
# Productionyarn build # Build for productionyarn start # Start production server
# Qualityyarn lint # Run ESLintyarn lint:fix # Auto-fix linting issuesyarn prettier # Format code with Prettieryarn ts # TypeScript type checkingyarn ts:watch # Watch mode type checking
# Maintenanceyarn rm:all # Clean all build artifacts and dependenciesyarn re:start # Fresh install and devyarn re:build # Fresh install and buildTechnology Stack
Section titled “Technology Stack”Core Framework
Section titled “Core Framework”- Next.js 13.5: React framework with App Router, SSR, and static generation
- React 18.2: UI library with hooks and concurrent features
- TypeScript 5.2: Static typing and enhanced IDE support
State Management
Section titled “State Management”- Redux Toolkit 1.9: Modern Redux with RTK Query
- Redux Persist 6.0: Automatic state persistence to localStorage
- React Redux 8.1: React bindings for Redux
UI and Styling
Section titled “UI and Styling”- Material-UI (MUI) 5.14: Component library with custom theme
- Emotion 11: CSS-in-JS styling solution
- Styled Components 6.0: Additional styling for custom components
- Framer Motion 10: Animation library for transitions
Forms and Validation
Section titled “Forms and Validation”- React Hook Form 7.47: Performant form management
- Yup 1.3: Schema validation
- @hookform/resolvers: Yup integration for RHF
Networking and Real-time
Section titled “Networking and Real-time”- Axios 1.5: HTTP client with interceptors
- WebSocket: Native WebSocket for real-time messaging
- JWT Decode 4.0: Token parsing and validation
Monitoring and Analytics
Section titled “Monitoring and Analytics”- Sentry 7.81: Error tracking and performance monitoring
- Hotjar: User behavior analytics and heatmaps
- Google Analytics: Web analytics (gtag.js)
Development Tools
Section titled “Development Tools”- ESLint 8.50: Code linting with Airbnb config
- Prettier 3.0: Code formatting
- TypeScript ESLint 6.7: TypeScript-specific linting rules
External Services
Section titled “External Services”- CDN: Image hosting at cdn.rnb.la and img-s.rnb.la
- WebSocket Server: wss://redngift-ws.rnb.la/connect
- REST API: Configured via NEXT_PUBLIC_HOST_API environment variable
Extensibility
Section titled “Extensibility”Adding a New Feature Module
Section titled “Adding a New Feature Module”To add a new feature (e.g., “Gift Recommendations”):
- Define domain types in
src/types/:
export interface Recommendation { id: number; itemId: number; score: number; reason: string;}- Create API handler in
src/services/handlers/:
import { getRequest } from 'src/services/httpClient/httpClient';
const getRecommendations = async (userId: number) => { const res = await getRequest(`recommendations/${userId}`); return res.data;};
export const recommendationsHandlers = { getRecommendations,};- Create Redux slice in
src/utils/redux/slices/:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const fetchRecommendations = createAsyncThunk( 'recommendations/fetch', async (userId: number) => { return await recommendationsHandlers.getRecommendations(userId); });
const recommendationsSlice = createSlice({ name: 'recommendations', initialState: { items: [], loading: false }, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchRecommendations.pending, (state) => { state.loading = true; }) .addCase(fetchRecommendations.fulfilled, (state, action) => { state.items = action.payload; state.loading = false; }); },});
export default recommendationsSlice.reducer;- Register slice in root reducer:
import recommendationsReducer from './slices/recommendationsSlice';
export const rootReducer = combineReducers({ // ... existing slices recommendations: persistReducer(persistConfig('recommendations'), recommendationsReducer),});- Create page section in
src/sections/:
'use client';
import { useEffect } from 'react';import { useDispatch, useSelector } from 'src/utils/redux/store';import { fetchRecommendations } from 'src/utils/redux/slices/recommendationsSlice';
export default function RecommendationsView() { const dispatch = useDispatch(); const { items, loading } = useSelector((state) => state.recommendations);
useEffect(() => { dispatch(fetchRecommendations(userId)); }, [dispatch]);
return <div>{/* Render recommendations */}</div>;}- Create route in
src/app/(home)/:
// src/app/(home)/recommendations/page.tsximport RecommendationsView from 'src/sections/recommendations/recommendations-view';
export default function RecommendationsPage() { return <RecommendationsView />;}- Add path definition in
src/routes/paths.ts:
export const paths = { home: { // ... existing paths recommendations: `${ROOTS.HOME}recommendations`, },};Testing Requirements
Section titled “Testing Requirements”- Write unit tests for Redux slices (actions, reducers, selectors)
- Test API handlers with mock responses
- Test React components with React Testing Library
- Integration tests for critical user flows
Assumption: Testing infrastructure not yet configured; add Jest and React Testing Library as needed.
Security and Compliance
Section titled “Security and Compliance”Authentication and Authorization
Section titled “Authentication and Authorization”- Authentication method: JWT tokens issued by backend after magic link login
- Token storage: localStorage (key:
accessToken) - Token refresh: Not implemented; users must re-authenticate after expiration
- Route protection:
AuthGuardwraps authenticated routes, redirects to/auth/loginif unauthenticated - API authorization: Axios interceptor attaches
Authorization: Bearer <token>header to all requests
Data Handling
Section titled “Data Handling”- PII collected: User name, email, phone number, profile photo
- PII storage: Backend only; frontend caches user data in Redux (ephemeral)
- Image uploads: Sent to backend, which handles CDN upload
- Third-party tracking: Sentry (error metadata), Hotjar (anonymized sessions), Google Analytics (pageviews)
- Data retention: Redux state cleared on logout; localStorage token removed
Security Considerations
Section titled “Security Considerations”- XSS protection: React’s default escaping; use
dangerouslySetInnerHTMLonly with sanitized content - CSRF: Not applicable (JWT in localStorage, not cookies)
- Sensitive data in logs: Sentry captures exceptions; avoid logging tokens or passwords
- Content Security Policy: Not configured; consider adding CSP headers in production
Assumption: Backend handles input validation, rate limiting, and SQL injection prevention.
Build and Deployment
Section titled “Build and Deployment”- Platform: Vercel (automatic deploys from Git)
- Environments:
- Development: Local (
yarn dev) - Preview: Vercel preview deployments for PRs
- Production: Vercel production deployment from
mainbranch
- Development: Local (
- Environment variables: Configured in Vercel dashboard
NEXT_PUBLIC_HOST_API: Backend API base URLNEXT_PUBLIC_ASSETS_API: CDN base URL- Sentry DSN and auth tokens
- Google Analytics ID
- Hotjar site ID
Release Process
Section titled “Release Process”- Merge feature branch to
mainvia pull request - Vercel automatically builds and deploys to production
- Sentry release tracking enabled via
@sentry/nextjsplugin - Source maps uploaded to Sentry for stack trace resolution
Assumption: No manual deployment steps; Vercel handles builds, CDN distribution, and rollbacks.
Monitoring
Section titled “Monitoring”- Error tracking: Sentry captures unhandled exceptions and API errors
- Performance: Sentry performance monitoring for slow transactions
- User analytics: Hotjar session recordings and Google Analytics pageviews
- Logs: Next.js server logs available in Vercel dashboard
Further Reading
Section titled “Further Reading”Concepts
Section titled “Concepts”- Authentication and Session Management
- State Management with Redux
- Real-time Communication
- Routing and Navigation
- API Layer and Data Fetching
- Error Handling and Monitoring
Features
Section titled “Features”- Secret Santa Groups
- Wishlist Management
- Item Management
- Group Invitations
- Real-time Chat
- Trending Items Discovery