Skip to main content

PictureThis Frontend Technical Documentation

Overview

PictureThis is a modern React-based web application built with Next.js 14, featuring AI-powered image generation capabilities. The frontend provides a user-friendly interface for image creation, user management, and administrative functions.

Architecture

Technology Stack

  • Framework: Next.js 14 (App Router)
  • Language: TypeScript
  • Styling: Tailwind CSS
  • UI Components: Custom components with shadcn/ui
  • State Management: React Context API
  • HTTP Client: Axios
  • Authentication: JWT tokens with HTTP-only cookies
  • Deployment: Railway (Vercel-compatible)

Project Structure

picfe/
├── src/
│ ├── app/ # Next.js App Router pages
│ │ ├── (auth)/ # Authentication routes
│ │ ├── (dashboard)/ # Protected user routes
│ │ ├── admin/ # Admin panel routes
│ │ ├── api/ # Next.js API routes
│ │ ├── payment/ # Payment flow pages
│ │ └── page.tsx # Home page
│ ├── components/ # Reusable UI components
│ │ ├── ui/ # Base UI components (shadcn)
│ │ └── *.tsx # Feature components
│ └── lib/ # Utilities and configurations
│ ├── api.tsx # API client and endpoints
│ ├── auth-context.tsx # Authentication context
│ └── utils.ts # Helper functions
├── public/ # Static assets
├── tailwind.config.js # Tailwind CSS configuration
├── next.config.mjs # Next.js configuration
└── package.json # Dependencies and scripts

Application Routes

Public Routes

RouteComponentDescription
/page.tsxLanding page with hero section
/aboutabout/page.tsxAbout page
/pricingpricing/page.tsxPricing plans
/termsterms/page.tsxTerms of service
/privacyprivacy/page.tsxPrivacy policy
/verify-emailverify-email/page.tsxEmail verification
/forgot-passwordforgot-password/page.tsxPassword reset

Authentication Routes

RouteComponentDescription
/login(auth)/login/page.tsxUser login
/register(auth)/register/page.tsxUser registration
/reset-passwordreset-password/page.tsxPassword reset

Protected User Routes

RouteComponentDescription
/dashboard(dashboard)/page.tsxUser dashboard
/gallery(dashboard)/gallery/page.tsxUser's image gallery
/generate(dashboard)/generate/page.tsxImage generation interface
/profile(dashboard)/profile/page.tsxUser profile management
/settings(dashboard)/settings/page.tsxUser settings

Payment Routes

RouteComponentDescription
/payment/redirectpayment/redirect/page.tsxPayment redirect
/payment/successpayment/success/page.tsxPayment success
/payment/cancelledpayment/cancelled/page.tsxPayment cancelled

Admin Routes

RouteComponentDescription
/adminadmin/page.tsxAdmin dashboard
/admin/usersadmin/users/page.tsxUser management
/admin/creditsadmin/credits/page.tsxCredit management
/admin/analyticsadmin/analytics/page.tsxAnalytics dashboard
/admin/settingsadmin/settings/page.tsxSystem settings

API Routes

RouteMethodDescription
/api/settingsGETPublic settings
/api/admin/settingsGET/PUTAdmin settings management

Core Components

Layout Components

Header.tsx

  • Navigation bar with authentication state
  • Responsive design with mobile menu
  • Credit balance display for authenticated users

Footer.tsx

  • Site footer with links
  • Social media links
  • Copyright information

ClientAppProviders.tsx

  • Root provider component
  • Wraps app with necessary contexts (Auth, Theme, etc.)
  • Handles client-side initialization

Authentication Components

AdminClientAuth.tsx

  • Admin authentication wrapper
  • Redirects non-admin users
  • Displays loading states

RequireVerification.tsx

  • Email verification requirement
  • Blocks access until email is verified
  • Provides verification prompts

PermissionModal.tsx

  • User permission consent modal
  • GDPR compliance for image usage tracking
  • Stores consent in database

UI Components

CreditStatus.tsx

  • Displays current credit balance
  • Shows credit usage statistics
  • Purchase credit prompts

PayFastModal.tsx

  • Payment modal for credit purchases
  • Integrates with PayFast payment gateway
  • Handles payment flow and callbacks

Form Components

LoginForm, RegisterForm

  • Authentication forms with validation
  • Error handling and loading states
  • Remember me functionality

ImageGenerationForm

  • AI model selection (Vision Studio, Pixel Forge)
  • Prompt input with enhancement
  • File upload for reference images
  • Generation progress tracking

API Integration

API Client (lib/api.tsx)

The frontend uses a centralized API client built on Axios with the following features:

Base Configuration

const api = axios.create({
baseURL: API_BASE_URL, // From NEXT_PUBLIC_API_URL
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
timeout: 480000, // 8 minutes for long AI requests
});

Request Interceptor

  • Automatically adds JWT token to requests
  • Retrieves token from localStorage
  • Handles token refresh logic

Response Interceptor

  • Global error handling
  • Token expiration handling
  • Automatic logout on 401 responses

API Endpoints

Authentication API

export const authAPI = {
login: (credentials: LoginCredentials) => api.post('/auth/login', credentials),
register: (userData: RegisterData) => api.post('/auth/register', userData),
verifyEmail: (token: string) => api.post('/auth/verify-email', { token }),
forgotPassword: (email: string) => api.post('/auth/forgot-password', { email }),
resetPassword: (data: ResetPasswordData) => api.post('/auth/reset-password', data),
getProfile: () => api.get('/auth/profile'),
};

User Management API

export const userAPI = {
getProfile: () => api.get('/users/profile'),
updateProfile: (data: UpdateProfileData) => api.put('/users/profile', data),
checkPermissions: (type: string) => api.get(`/users/permissions/${type}`),
updatePermissions: (type: string, accepted: boolean) => api.post(`/users/permissions/${type}`, { accepted }),
};

Image Generation API

export const imageAPI = {
generate: (formData: FormData) => api.post('/images/generate', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
}),
getGallery: () => api.get('/images/gallery'),
getMyImages: (params?: PaginationParams) => api.get('/images/my-images', { params }),
upload: (file: File) => {
const formData = new FormData();
formData.append('image', file);
return api.post('/images/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
},
download: (imageId: string) => api.get(`/images/${imageId}/download`, {
responseType: 'blob'
}),
};

Pixel Forge API

export const wan25API = {
generate: (formData: FormData) => api.post('/wan25/generate', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
}),
};

Credits API

export const creditsAPI = {
getBalance: () => api.get('/credits/balance'),
purchase: (data: PurchaseData) => api.post('/credits/purchase', data),
getHistory: (params?: PaginationParams) => api.get('/credits/history', { params }),
};

Prompt Enhancement API

export const promptAPI = {
startEnhancement: (data: { initialPrompt: string }) => api.post('/prompts/enhance/start', data),
continueEnhancement: (data: EnhancementData) => api.post('/prompts/enhance/continue', data),
endEnhancement: (data: FinalPromptData) => api.post('/prompts/enhance/end', data),
};

Admin API

export const adminAPI = {
// User management
getUsers: (params?: UserFilters) => api.get('/admin/users', { params }),
updateUser: (userId: string, data: UpdateUserData) => api.put(`/admin/users/${userId}`, data),
deleteUser: (userId: string) => api.delete(`/admin/users/${userId}`),
updateUserAdminStatus: (userId: string, isAdmin: boolean) => api.put(`/admin/users/${userId}/admin`, { isAdmin }),

// Credits management
getCreditTransactions: (params?: PaginationParams) => api.get('/admin/credits/transactions'),
addUserCredits: (data: AddCreditsData) => api.post('/admin/users/credits', data),
setUserCredits: (data: SetCreditsData) => api.post('/admin/users/credits', { ...data, setCredits: true }),

// Settings
getCreditSettings: () => api.get('/admin/settings/credits'),
updateCreditSettings: (settings: CreditSettings) => api.put('/admin/settings/credits', settings),
getSettings: () => api.get('/admin/settings'),
updateSettings: (settings: SystemSettings) => api.put('/admin/settings', { settings }),
deleteSetting: (key: string) => api.delete(`/admin/settings/${key}`),

// Analytics
getImageLifecycleStats: () => api.get('/admin/image-lifecycle/stats'),
getImageDeletionPreview: () => api.get('/admin/image-lifecycle/preview'),
performSoftDelete: () => api.post('/admin/image-lifecycle/soft-delete'),
performHardDelete: () => api.post('/admin/image-lifecycle/hard-delete'),
};

Authentication System

JWT Token Management

  • Storage: localStorage for token persistence
  • Automatic Inclusion: Request interceptor adds Bearer token
  • Expiration Handling: Automatic logout on 401 responses
  • Refresh Logic: Token refresh on expiration

Route Protection

Client-side Protection

// In components that require authentication
const { user, loading } = useAuth();

if (loading) return <LoadingSpinner />;
if (!user) {
redirect('/login');
return null;
}

Server-side Protection (Middleware)

// middleware.ts
export function middleware(request: NextRequest) {
const token = request.cookies.get('token')?.value;

if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
}

Admin Authorization

// Admin route protection
const { user } = useAuth();

if (!user?.isAdmin) {
return <AccessDenied />;
}

State Management

Authentication Context

interface AuthContextType {
user: User | null;
login: (credentials: LoginCredentials) => Promise<void>;
logout: () => void;
loading: boolean;
}

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);

// Authentication logic...
};

Global State

  • User Session: Authentication state and user data
  • UI State: Loading states, modals, notifications
  • Cache: API response caching for performance

Configuration

Environment Variables

Required

  • NEXT_PUBLIC_API_URL: Backend API base URL
  • NEXTAUTH_SECRET: NextAuth.js secret
  • NEXTAUTH_URL: Application URL

Optional

  • NODE_ENV: Environment (development/production)
  • NEXT_PUBLIC_APP_NAME: Application name
  • NEXT_PUBLIC_APP_VERSION: Application version

Build Configuration

next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
},
images: {
domains: ['your-s3-domain.com'],
},
async rewrites() {
return [
{
source: '/api/:path*',
destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`,
},
];
},
};

export default nextConfig;

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
primary: '#your-brand-color',
secondary: '#your-secondary-color',
},
},
},
plugins: [],
};

Performance Optimizations

Image Optimization

  • Next.js Image component for automatic optimization
  • WebP format support
  • Lazy loading
  • Responsive images

Code Splitting

  • Route-based code splitting (App Router)
  • Dynamic imports for heavy components
  • Bundle analysis and optimization

Caching Strategy

  • API response caching (30-second TTL)
  • Static asset caching
  • Service worker for offline functionality

Bundle Optimization

  • Tree shaking
  • Code minification
  • Compression (gzip/brotli)

Error Handling

Global Error Boundary

class ErrorBoundary extends React.Component {
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// Log error to monitoring service
console.error('Application Error:', error, errorInfo);
}

render() {
// Error UI
}
}

API Error Handling

try {
const response = await api.get('/endpoint');
return response.data;
} catch (error) {
if (error.response?.status === 401) {
// Handle unauthorized
logout();
} else if (error.response?.status === 403) {
// Handle forbidden
showError('Insufficient permissions');
} else {
// Handle other errors
showError('An error occurred');
}
}

Testing

Testing Strategy

  • Unit Tests: Component and utility function testing
  • Integration Tests: API integration testing
  • E2E Tests: User flow testing with Playwright/Cypress

Test Structure

__tests__/
├── components/ # Component tests
├── lib/ # Utility tests
├── pages/ # Page tests
└── e2e/ # End-to-end tests

Deployment

Build Process

npm run build    # Production build
npm run start # Production server
npm run dev # Development server

Railway Deployment

  • Automatic deployment on git push
  • Environment variable management
  • Build optimization for production
  • CDN integration for static assets

Performance Monitoring

  • Core Web Vitals tracking
  • Error monitoring (Sentry)
  • Performance metrics
  • User analytics

Security Features

Content Security Policy

// next.config.mjs
const csp = `
default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
`;

module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: csp.replace(/\s{2,}/g, ' ').trim(),
},
],
},
];
},
};

Input Validation

  • Client-side validation with react-hook-form
  • Server-side validation on API endpoints
  • Sanitization of user inputs

Authentication Security

  • JWT tokens with expiration
  • Secure token storage
  • CSRF protection
  • Rate limiting

Accessibility

WCAG Compliance

  • Semantic HTML
  • ARIA labels and roles
  • Keyboard navigation
  • Screen reader support
  • Color contrast compliance

Implementation

// Accessible button
<button
aria-label="Generate image"
aria-describedby="generation-description"
>
Generate
</button>

// Screen reader description
<div id="generation-description" className="sr-only">
Generate an AI image based on your text prompt
</div>

Browser Support

  • Modern Browsers: Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
  • Mobile: iOS Safari 14+, Chrome Mobile 90+
  • Progressive Enhancement: Graceful degradation for older browsers

Monitoring and Analytics

Application Monitoring

  • Error Tracking: Sentry for error monitoring
  • Performance: Web Vitals tracking
  • User Analytics: Plausible/Google Analytics
  • Uptime Monitoring: External monitoring services

Logging

  • Client-side error logging
  • API request/response logging
  • User action tracking
  • Performance metrics logging

Development Workflow

Local Development

npm install          # Install dependencies
npm run dev # Start development server
npm run build # Production build
npm run lint # Code linting
npm run test # Run tests

Code Quality

  • ESLint for code linting
  • Prettier for code formatting
  • TypeScript for type checking
  • Husky for pre-commit hooks

Git Workflow

  • Feature branches
  • Pull request reviews
  • Automated testing on CI/CD
  • Semantic versioning

Troubleshooting

Common Issues

API Connection Issues

  • Check NEXT_PUBLIC_API_URL environment variable
  • Verify backend service is running
  • Check network connectivity

Authentication Problems

  • Clear localStorage and cookies
  • Check JWT token expiration
  • Verify backend authentication endpoints

Build Failures

  • Clear .next cache
  • Check Node.js version compatibility
  • Verify all dependencies are installed

Performance Issues

  • Check bundle size with npm run analyze
  • Optimize images and assets
  • Implement code splitting for large components

Future Enhancements

Planned Features

  • PWA Support: Service worker implementation
  • Offline Mode: Cached content for offline use
  • Real-time Updates: WebSocket integration
  • Advanced Analytics: User behavior tracking
  • Multi-language Support: Internationalization
  • Theme Customization: User-selectable themes

Technical Debt

  • Migrate remaining pages to App Router
  • Implement comprehensive test coverage
  • Optimize bundle size further
  • Add end-to-end testing suite