Skip to content

SlothCodeSloth/BlogFrontend

Repository files navigation

Personal Website Frontend

A modern React frontend for a personal portfolio and blog website featuring project showcases, blog management, and secure user authentication. Built with TypeScript and Vite for performance and developer experience.

🎯 Overview

This frontend application serves as an interactive personal website with three main sections: an About Me page, a Projects portfolio, and a Personal Blog. It connects to a Spring Boot backend via REST API for content management and uses JWT-based authentication for secure administrative access.


✨ Features

πŸ“„ Content Sections

  • About Me: Personal introduction, skills showcase, and professional background
  • Projects Portfolio: Blog dedicated to Professional Projects with descriptions, technologies, and GitHub links
  • Blog Platform: Blog dedicated to personal life and miscallenous subjects
  • Responsive Design: Seamless experience across desktop, tablet, and mobile devices

πŸ” Authentication & Security

  • JWT Authentication: Secure login/logout with token based sessions
  • Protected Routes: Administrative functions restricted to authenticated users
  • XSS Prevention: DOMPurify HTML sanitization for safe content rendering
  • Token Management: Automatic token storage, validation, and refresh handling
  • Secure Headers: CORS and security best practices implementation

✍️ Content Management

  • Rich Text Editor: TipTap editor with formatting, lists, and code blocks
  • Image Upload: Drag and drop + copy-paste image functionality
  • Post Management: Full CRUD operations for blog posts and projects
  • Content Preview: Real time preview during editing
  • Infinite Scroll: Progressive content loading for optimal performance

⚑ Performance & UX

  • TypeScript Integration: Complete type safety across components
  • Optimized Loading: Code splitting, lazy loading, and efficient state management
  • Fast Builds: Vite for quick and optimized production builds
  • Loading States: Skeleton screens and progress indicators

πŸ—οΈ Tech Stack

Category Technology Purpose
Framework React Component-based UI development
Build Tool Vite Fast development server and optimized builds
Language TypeScript Type safety and enhanced DX
Routing React Router Client-side navigation and route protection
HTTP Client Axios API communication with interceptors
Rich Text TipTap Extensible rich text editor
Sanitization DOMPurify XSS prevention for user content
Icons React Icons Consistent iconography
Styling CSS3 Custom responsive styling with CSS variables

πŸ“‚ Project Structure

Frontend Source

src/
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ usePostActions.ts      # Custom hook for post CRUD operations
β”œβ”€β”€ App.tsx                    # Main application component
β”œβ”€β”€ PostDetail.tsx             # Individual post display
β”œβ”€β”€ PostEditor.tsx             # TipTap rich text editor wrapper
β”œβ”€β”€ PostForm.tsx               # Post creation/edit form with validation
β”œβ”€β”€ LoginComponent.tsx         # User authentication interface
└── SafeHTML.tsx               # Sanitized HTML renderer component
β”œβ”€β”€ CreatePostPage.tsx         # New post creation page
└── EditPostPage.tsx           # Post editing interface
└── api.ts                     # Axios configuration and API calls
└── App.css                    # Global styles and components
└── index.ts                   # TypeScript type definitions

Docker Deployment Structure

deployment/
β”œβ”€β”€ appdata/
β”‚   └── blog_frontend/             # Production build output (dist/)
β”œβ”€β”€ docker-compose.yml             # Docker orchestration configuration
β”œβ”€β”€ nginx.conf                     # Nginx reverse proxy configuration
└── postgres-data/                 # PostgreSQL data volume (mounted)

πŸš€ Getting Started

Prerequisites

  • Node.js: 18.x or higher
  • npm: 9.x or higher (or yarn/pnpm)
  • Backend API: Running Spring Boot backend (see Backend Repository)

Installation

  1. Clone the repository

    git clone https://github.com/your-username/personal-website-frontend.git
    cd personal-website-frontend
  2. Install dependencies

    npm install
  3. Configure environment variables

    Create a .env file in the root directory:

    VITE_API_BASE_URL=http://localhost:8080/api
    VITE_APP_NAME=Personal Website
  4. Verify API configuration (optional)

    Check src/services/api.ts for correct backend URL:

    const api = axios.create({
      baseURL: import.meta.env.VITE_API_BASE_URL || "http://localhost:8080/api",
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  5. Start development server

    npm run dev

    The application will be available at http://localhost:5173

Development Commands

# Start development server with HMR
npm run dev

# Build for production
npm run build

# Preview production build locally
npm run preview

πŸ”Œ API Integration

This frontend communicates with the Spring Boot backend via REST API. See the Backend Repository for reference.

Authentication Endpoints

// Login
POST /api/auth/login
Body: { username: string, password: string }
Response: { token: string, user: { id: number, username: string } }

Content Endpoints

// Get paginated posts
GET /api/posts?page=0&size=10&type=blog|project
Response: { content: Post[], totalPages: number, totalElements: number }

// Get single post
GET /api/posts/{id}
Response: Post

// Create post (authenticated)
POST /api/posts
Headers: { Authorization: "Bearer <token>" }
Body: { title: string, content: string, type: string, imageUrls?: string[] }
Response: Post

// Update post (authenticated)
PUT /api/posts/{id}
Headers: { Authorization: "Bearer <token>" }
Body: { title: string, content: string, type: string }
Response: Post

// Delete post (authenticated)
DELETE /api/posts/{id}
Headers: { Authorization: "Bearer <token>" }
Response: 204 No Content

Axios Interceptors

The application uses request and response interceptors for:

  • Request Interceptor: Automatically attaches JWT token to protected requests
  • Response Interceptor: Handles 401 errors and redirects to login
  • Error Handling: Standardized error responses across the application

πŸ”‘ Key Components

Authentication System

  • LoginComponent: Form based authentication with validation and error handling
  • ProtectedRoute: Redirects unauthenticated users
  • Token Storage: localStorage-based token persistence with automatic injection

Content Creation & Management

  • PostEditor: TipTap editor supporting:
    • Text formatting (bold, italic, underline)
    • Headings and paragraphs
    • Lists (ordered and unordered)
    • Code blocks with syntax highlighting
    • Image embedding via upload or paste
  • PostForm: Unified form for creating/editing with real-time validation
  • usePostActions: Custom hook abstracting CRUD operations with error handling

Security & Rendering

  • SafeHTML: Component wrapper using DOMPurify to sanitize user-generated HTML
  • XSS Protection: All rich text content sanitized before rendering
  • CSRF Protection: Token-based authentication prevents CSRF attacks

User Experience

  • Infinite Scroll: Intersection Observer API for automatic pagination
  • Loading States: Skeleton screens during data fetching
  • Error Boundaries: Graceful degradation on component errors

πŸ›‘οΈ Security Best Practices

Implemented Security Measures

  • JWT Authentication: Stateless authentication with expiration
  • HTML Sanitization: DOMPurify prevents XSS attacks in user content
  • Protected Routes: Client side route guards for authenticated pages
  • Secure Storage: Tokens stored in localStorage (consider httpOnly cookies for production)
  • HTTPS: Production deployment requires SSL/TLS
  • CORS Configuration: Backend configured to accept requests only from known origins

🐳 Docker Deployment

Production Build

  1. Build optimized production bundle

    npm run build

    Output will be in dist/ directory

  2. Copy to Docker volume

    cp -r dist/* /path/to/appdata/blog_frontend/
  3. Configure Nginx

    Update nginx.conf with your domain and SSL certificates:

    server {
        listen 80;
        server_name your-domain.com;
        
        location / {
            root /usr/share/nginx/html;
            try_files $uri $uri/ /index.html;
        }
        
        location /api {
            proxy_pass http://backend:8080;
        }
    }
  4. Start Docker services

    docker-compose up -d

Environment Variables for Production

VITE_API_BASE_URL=https://your-domain.com/api
VITE_APP_NAME=Your Website Name

πŸ”— Related Repositories

  • Backend: Personal Website Backend
    Spring Boot REST API with JWT authentication, PostgreSQL database, and comprehensive documentation

  • Database: Docker Setup
    Docker file containing setup for PostgreSQL Database


πŸ“ˆ Performance Optimization

Implemented Optimizations

  • Code Splitting: Dynamic imports for route based splitting
  • Lazy Loading: Images and components loaded on demand
  • Bundle Optimization: Vite's rollup bundler with tree shaking
  • Asset Optimization: Image compression and lazy loading

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸš€ Future Enhancements

  • Dark/light theme toggle
  • Advanced search with filters (tags, date range, content type)
  • Comment system for blog posts
  • Markdown support alongside rich text

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages