# M3: Setup Frontend ## Prompt Create the frontend infrastructure for **newzy** news web application using React + TypeScript with Vite. Follow these steps: 1. Set up project structure in `frontend/` folder: ``` newzy/ ├── frontend/ │ ├── public/ │ ├── src/ │ │ ├── components/ │ │ │ └── Header.tsx │ │ ├── pages/ │ │ │ └── Home.tsx │ │ ├── types/ │ │ │ └── index.ts │ │ ├── api/ │ │ │ └── client.ts │ │ ├── App.tsx │ │ └── main.tsx │ ├── .gitignore │ ├── Dockerfile │ ├── docker-compose.yml │ ├── package.json │ ├── tsconfig.json │ ├── vite.config.ts │ └── README.md ``` 2. Initialize Vite project with React and TypeScript template: - Use Node.js 18 or later - Install dependencies: react, react-dom, typescript, @types/react, @types/react-dom, vite 3. Configure Vite with: - Base path configuration - Build output directory (dist/) - Development server on port 5173 4. Create TypeScript type definitions in `src/types/`: - Article interface (id, title, content, author, category, published, createdAt) - Author interface (id, name, email, bio) - Category interface (id, name, slug) - API response types 5. Create React components: - `Header.tsx` with logo and navigation placeholder - `Home.tsx` page component for listing articles - Reusable UI components (ArticleCard, AuthorAvatar, CategoryBadge) 6. Set up API client in `src/api/client.ts`: - Base URL configuration (relative path /api) - Fetch wrapper with error handling - Type-safe request/response functions 7. Create `package.json` scripts: - dev: Development server - build: Production build - preview: Preview production build - lint: ESLint check 8. Create `.gitignore` to exclude node_modules, dist/, .env files, IDE configs 9. Create `Dockerfile` for React + Vite with: - Node.js base image - Install dependencies - Build frontend - Nginx layer for serving static files in production - Multi-stage build for optimization 10. Update `docker-compose.yml` at project root with frontend service: - Port mapping 3000:80 - Links to backend service for API calls 11. Document setup process in `frontend/README.md` with examples 12. Configure ESLint rules in .eslintrc.cjs or vite.config.ts Remember: Focus ONLY on frontend infrastructure. No complex UI features required yet. ## Description This milestone sets up the React + TypeScript frontend for newzy news application using Vite as the build tool. The scope includes project scaffolding, type definitions, basic components, and Docker containerization—no complex UI implementations or user interactions. **Purpose**: Create a responsive, type-safe frontend ready to consume the backend API built in M2. **Target Audience**: Frontend developers who need to understand the structure and extend components for features in subsequent milestones. **Expected Outcomes**: A functioning React application that can load from browser or Docker container, with typed interfaces matching backend models and basic page layout in place. ## Acceptance Criteria - [ ] Vite project initialized with React and TypeScript - [ ] Project structure includes: public/, src/, components/, pages/, types/, api/ folders - [ ] TypeScript type definitions for Article, Author, Category models - [ ] Header component created with navigation placeholder - [ ] Home page component rendering article listing layout - [ ] API client configured with base URL and fetch wrapper - [ ] package.json has dev, build, preview scripts working correctly - [ ] .gitignore excludes node_modules, dist/, IDE configs - [ ] Dockerfile builds production-ready static files - [ ] docker-compose.yml includes frontend service linked to backend - [ ] Nginx configuration in Dockerfile for serving built files - [ ] ESLint rules configured and passing ## Technical Details ### Project Root Structure ``` newzy/ ├── frontend/ │ ├── public/ │ │ └── index.html # Vite entry HTML file │ ├── src/ │ │ ├── assets/ │ │ │ ├── styles.css # Global styles │ │ │ └── logo.svg # Brand logo (placeholder) │ │ ├── components/ │ │ │ └── Header.tsx # Main navigation header │ │ ├── pages/ │ │ │ └── Home.tsx # Homepage with article feed │ │ ├── types/ │ │ │ └── index.ts # TypeScript interfaces │ │ ├── api/ │ │ │ └── client.ts # API request wrapper │ │ ├── App.tsx # Root component │ │ └── main.tsx # React entry point │ ├── .gitignore │ ├── Dockerfile │ ├── docker-compose.yml # Frontend service config │ ├── package.json │ ├── tsconfig.json │ ├── vite.config.ts │ └── README.md # Setup and API documentation ├── backend/ # Backend from M2 ├── LICENSE # MIT License ├── README.md # Main project docs └── docker-compose.yml # Full application orchestration ``` ### TypeScript Type Definitions ```typescript // src/types/index.ts export interface Article { id: number; title: string; content: string; authorId: number; author?: Author; categoryId: number; category?: Category; createdAt: string; published: boolean; } export interface Author { id: number; name: string; email: string; bio?: string; } export interface Category { id: number; name: string; slug: string; } export interface ApiResponse { success: boolean; data?: T; error?: string; message?: string; } ``` ### API Client Configuration ```typescript // src/api/client.ts const API_BASE_URL = '/api'; async function fetchApi(endpoint: string): Promise> { try { const response = await fetch(`${API_BASE_URL}${endpoint}`); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } return await response.json(); } catch (error) { console.error('API request failed:', error); throw error; } } export const apiClient = { getArticles: () => fetchApi('/articles'), getArticle: (id: number) => fetchApi
(`/articles/${id}`), getCategories: () => fetchApi('/categories'), }; ``` ### package.json Scripts ```json { "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview", "lint": "eslint src/" } } ``` ### Dockerfile (Multi-stage Build) **Stage 1 - Build:** ```dockerfile FROM node:20-alpine AS build WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build ``` **Stage 2 - Serve:** ```dockerfile FROM nginx:alpine COPY --from=build /app/dist /usr/share/nginx/html COPY nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` ### Nginx Configuration ```nginx server { listen 80; server_name localhost; root /usr/share/nginx/html; index index.html; location / { try_files $uri $uri/ /index.html; } } ``` ### docker-compose.yml (project root) ```yaml version: '3.8' services: backend: build: ./backend ports: - "8000:8000" volumes: - ./data/db:/app/data/db environment: - DATABASE_URL=sqlite:///./data/db/newzy.db frontend: build: ./frontend ports: - "3000:80" depends_on: - backend ``` ### ESLint Configuration Rules - No unused variables or imports - TypeScript strict mode enabled - Consistent indentation (2 spaces) - No console.log in production code - Prefer arrow functions for callbacks ## QA Notes ### Testing Checklist - [ ] npm install completes without errors - [ ] npm run dev starts Vite dev server successfully - [ ] npm run build creates dist/ folder with all assets - [ ] TypeScript compilation passes (no errors) - [ ] ESLint check passes on codebase - [ ] Components render correctly in browser - [ ] API client returns properly typed responses - [ ] Docker image builds without warnings - [ ] Frontend container serves index.html at root - [ ] nginx configuration routes requests to React SPA ### Performance Considerations - Vite uses ESBuild for fast HMR during development - TypeScript checks on build, not incremental dev - Nginx serves static files efficiently in production - Multi-stage Docker builds reduce image size ### Security Notes - No sensitive data in client-side code - API credentials should use backend proxy (not direct fetch) - CORS must be configured on backend to accept frontend origin - CSRF protection TBD for future milestones ### Known Issues / Limitations - No authentication flow implemented yet - Static file serving requires nginx restart on rebuild - Vite HMR doesn't work in Docker without hot-reload support - TypeScript path aliases not configured (using relative imports) ### Success Metrics - `npm run dev` starts within 30 seconds - `npm run build` produces <10MB production bundle - TypeScript compilation completes under 5 minutes - Docker frontend image size <200MB - All ESLint rules pass with zero warnings in critical code - Browser console has no errors on page load