Skip to content

sontt9/frontend-base

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Modern Frontend Boilerplate

A production-ready React + TypeScript frontend boilerplate featuring cutting-edge technologies and enterprise-grade architecture patterns.

✨ Key Features

πŸ—οΈ Modern Architecture

  • ⚑ Vite 6 - Lightning-fast build tool with HMR and optimized bundling
  • βš›οΈ React 19 - Latest React with concurrent features and new hooks
  • πŸ“˜ TypeScript 5.8 - Strict type safety with advanced configurations
  • 🎨 Tailwind CSS v4 - Next-generation utility-first CSS with new engine

πŸ”§ Developer Experience

  • πŸ”€ React Router v7 - Type-safe client-side routing
  • 🎯 ESLint + Prettier - Comprehensive code quality with flat config
  • πŸ• Husky + lint-staged - Automated git hooks for quality control
  • πŸ›‘οΈ Error Boundaries - Graceful error handling and recovery
  • πŸŒ™ Dark Mode - Advanced theme system with system preference detection

🎨 UI/UX Excellence

  • 🎭 shadcn/ui - Beautiful, accessible component library
  • πŸ“± Responsive Design - Mobile-first approach with Tailwind breakpoints
  • πŸŽͺ Design System - Comprehensive CSS variables and design tokens
  • ⚑ Performance - Web Vitals monitoring and optimization utilities

πŸ”’ Production Ready

  • πŸ›‘οΈ Type Safety - Comprehensive TypeScript coverage
  • πŸ“Š Performance Monitoring - Web Vitals and custom metrics
  • πŸͺ State Management - Architecture ready for Zustand/Redux
  • πŸ”§ Environment Config - Proper environment variable handling

πŸ› οΈ Tech Stack

Category Technology Version Purpose
Frontend React 19.1.0 UI library with latest features
Language TypeScript 5.8.3 Type-safe JavaScript
Build Tool Vite 6.3.5 Fast development and building
Styling Tailwind CSS 4.1.8 Utility-first CSS framework
Routing React Router 7.6.2 Client-side navigation
UI Components shadcn/ui Latest Accessible component library
Linting ESLint 9.18.0 Code quality and consistency
Formatting Prettier 3.4.2 Code formatting
Git Hooks Husky 9.1.7 Automated quality checks

πŸš€ Quick Start

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 9.0.0 or yarn >= 1.22.0
  • Git for version control

Installation

# Clone the repository
git clone <your-repo-url>
cd frontend-boilerplate

# Install dependencies
npm install

# Copy environment variables template
cp .env.example .env.local

# Start development server
npm run dev

Development Commands

# Development
npm run dev          # Start dev server (http://localhost:5173)
npm run dev:host     # Start dev server with network access

# Building
npm run build        # Production build
npm run preview      # Preview production build locally

# Code Quality
npm run lint         # Run ESLint
npm run lint:fix     # Fix ESLint issues automatically
npm run format       # Format code with Prettier
npm run type-check   # Run TypeScript compiler check

# Testing (when implemented)
npm run test         # Run tests
npm run test:watch   # Run tests in watch mode
npm run test:coverage # Generate coverage report

πŸ“ Project Architecture

Directory Structure

src/
β”œβ”€β”€ components/          # Reusable UI components
β”‚   β”œβ”€β”€ ui/             # shadcn/ui components
β”‚   └── common/         # Custom shared components
β”œβ”€β”€ page/               # Page-level components
β”‚   β”œβ”€β”€ Home/          # Home page components
β”‚   β”œβ”€β”€ Error/         # Error page components
β”‚   └── NotFound/      # 404 page components
β”œβ”€β”€ hooks/              # Custom React hooks
β”‚   β”œβ”€β”€ useTheme.ts    # Theme management hook
β”‚   └── index.ts       # Hook exports
β”œβ”€β”€ lib/                # Utility libraries
β”‚   β”œβ”€β”€ utils.ts       # Tailwind utilities (cn function)
β”‚   └── validations.ts # Form validation schemas
β”œβ”€β”€ store/              # State management
β”‚   β”œβ”€β”€ slices/        # Redux/Zustand slices
β”‚   └── index.ts       # Store configuration
β”œβ”€β”€ types/              # TypeScript type definitions
β”‚   β”œβ”€β”€ api.ts         # API response types
β”‚   β”œβ”€β”€ components.ts  # Component prop types
β”‚   └── index.ts       # Common types
β”œβ”€β”€ utils/              # Helper utilities
β”‚   β”œβ”€β”€ api.ts         # API utilities
β”‚   β”œβ”€β”€ performance.ts # Performance monitoring
β”‚   β”œβ”€β”€ storage.ts     # LocalStorage helpers
β”‚   └── index.ts       # Utility exports
β”œβ”€β”€ constants/          # Application constants
β”‚   β”œβ”€β”€ routes.ts      # Route definitions
β”‚   β”œβ”€β”€ config.ts      # App configuration
β”‚   └── index.ts       # Constant exports
β”œβ”€β”€ styles/             # Global styles and themes
β”‚   β”œβ”€β”€ globals.css    # Global CSS styles
β”‚   └── components.css # Component-specific styles
└── main.tsx           # Application entry point

Component Architecture

components/
β”œβ”€β”€ ui/                 # Base UI components (shadcn/ui)
β”‚   β”œβ”€β”€ Button/
β”‚   β”œβ”€β”€ Input/
β”‚   β”œβ”€β”€ Card/
β”‚   └── ...
β”œβ”€β”€ common/             # Shared business components
β”‚   β”œβ”€β”€ Header/
β”‚   β”œβ”€β”€ Footer/
β”‚   β”œβ”€β”€ Layout/
β”‚   └── ErrorBoundary/
└── forms/              # Form-specific components
    β”œβ”€β”€ ContactForm/
    β”œβ”€β”€ LoginForm/
    └── ...

🎨 Design System

Theme Configuration

The project uses a comprehensive design system with CSS variables for consistent theming:

:root {
  /* Color palette */
  --background: 0 0% 100%;
  --foreground: 20 14.3% 4.1%;
  --primary: 24 9.8% 10%;
  --secondary: 60 4.8% 95.9%;

  /* Component colors */
  --card: 0 0% 100%;
  --border: 20 5.9% 90%;
  --input: 20 5.9% 90%;

  /* Interactive states */
  --ring: 20 14.3% 4.1%;
  --radius: 0.5rem;
}

Dark Mode Support

// Automatic theme detection with system preference
const { theme, setTheme, isDark } = useTheme();

// Available themes: 'light', 'dark', 'system'
setTheme("dark");

Responsive Breakpoints

// Tailwind CSS breakpoints
const breakpoints = {
  sm: '640px',   // Mobile landscape
  md: '768px',   // Tablet
  lg: '1024px',  # Desktop
  xl: '1280px',  # Large desktop
  '2xl': '1536px' # Extra large desktop
};

πŸ”§ Configuration

Environment Variables

Create a .env.local file from the template:

# Application Configuration
VITE_APP_NAME="Your App Name"
VITE_APP_VERSION="1.0.0"

# API Configuration
VITE_API_BASE_URL="https://api.yourdomain.com"
VITE_API_TIMEOUT="10000"

# Feature Flags
VITE_ENABLE_ANALYTICS="false"
VITE_ENABLE_ERROR_REPORTING="false"

# External Services
VITE_ANALYTICS_ID=""
VITE_SENTRY_DSN=""

TypeScript Configuration

// tsconfig.json highlights
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

Vite Configuration

// Key Vite configurations
export default defineConfig({
  plugins: [
    react(),
    tailwindcss(), // Tailwind CSS v4 plugin
  ],
  resolve: {
    alias: { "@": path.resolve(__dirname, "./src") },
  },
  build: {
    target: "esnext",
    minify: "esbuild",
    sourcemap: true,
  },
});

πŸ—οΈ Architecture Patterns

Component Composition

This boilerplate follows composition over inheritance patterns:

// Higher-Order Component pattern
const withAuth = <P extends object>(Component: React.ComponentType<P>) => {
  return (props: P) => {
    const { isAuthenticated } = useAuth();
    return isAuthenticated ? <Component {...props} /> : <LoginRedirect />;
  };
};

// Render props pattern
const DataProvider = ({ children, url }: DataProviderProps) => {
  const { data, loading, error } = useFetch(url);
  return children({ data, loading, error });
};

// Compound component pattern
const Modal = ({ children, isOpen, onClose }: ModalProps) => {
  return isOpen ? (
    <div className="modal-overlay" onClick={onClose}>
      {children}
    </div>
  ) : null;
};

State Management Strategy

// Local state for component-specific data
const [isOpen, setIsOpen] = useState(false);

// Global state for shared application data
const useGlobalStore = create<GlobalState>((set) => ({
  user: null,
  theme: "system",
  setUser: (user) => set({ user }),
  setTheme: (theme) => set({ theme }),
}));

// Server state for API data
const { data, isLoading, error } = useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
});

Error Handling Architecture

// Component-level error boundaries
<ErrorBoundary fallback={<ErrorFallback />}>
  <SuspenseWrapper>
    <LazyComponent />
  </SuspenseWrapper>
</ErrorBoundary>

// Global error handling
window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
  // Send to error reporting service
});

⚑ Performance Optimization

Code Splitting

// Route-based splitting
const Home = lazy(() => import("./pages/Home"));
const Dashboard = lazy(() => import("./pages/Dashboard"));

// Component-based splitting
const HeavyChart = lazy(() => import("./components/HeavyChart"));

// Conditional loading
const AdminPanel = lazy(() =>
  import("./components/AdminPanel").then((module) => ({
    default: module.AdminPanel,
  }))
);

Performance Monitoring

// Web Vitals integration
import { reportWebVitals } from "./utils/performance";

// Development monitoring
if (process.env.NODE_ENV === "development") {
  reportWebVitals(console.log);
}

// Production analytics
if (process.env.NODE_ENV === "production") {
  reportWebVitals(sendToAnalytics);
}

Bundle Optimization

// Vite build configuration for optimal bundles
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ["react", "react-dom"],
          router: ["react-router-dom"],
          ui: ["@radix-ui/react-dialog", "@radix-ui/react-dropdown-menu"],
        },
      },
    },
  },
});

πŸ§ͺ Testing Strategy

Unit Testing

// Component testing with React Testing Library
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from './Button';

describe('Button Component', () => {
  it('renders with correct text', () => {
    render(<Button>Click me</Button>);
    expect(screen.getByRole('button')).toHaveTextContent('Click me');
  });

  it('calls onClick when clicked', () => {
    const handleClick = vi.fn();
    render(<Button onClick={handleClick}>Click me</Button>);
    fireEvent.click(screen.getByRole('button'));
    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

Integration Testing

// Custom hooks testing
import { renderHook, act } from "@testing-library/react";
import { useTheme } from "./useTheme";

describe("useTheme Hook", () => {
  it("initializes with system theme", () => {
    const { result } = renderHook(() => useTheme());
    expect(result.current.theme).toBe("system");
  });

  it("updates theme correctly", () => {
    const { result } = renderHook(() => useTheme());
    act(() => {
      result.current.setTheme("dark");
    });
    expect(result.current.theme).toBe("dark");
  });
});

πŸ” Security Best Practices

Environment Security

// Secure environment variable handling
const config = {
  apiUrl: import.meta.env.VITE_API_BASE_URL,
  version: import.meta.env.VITE_APP_VERSION,
  // Never expose sensitive keys in VITE_ variables
  internalApiKey: process.env.INTERNAL_API_KEY, // Server-side only
};

// Runtime environment validation
const requiredEnvVars = ["VITE_API_BASE_URL", "VITE_APP_NAME"];
requiredEnvVars.forEach((envVar) => {
  if (!import.meta.env[envVar]) {
    throw new Error(`Missing required environment variable: ${envVar}`);
  }
});

Content Security Policy

<!-- Recommended CSP headers -->
<meta
  http-equiv="Content-Security-Policy"
  content="
  default-src 'self';
  script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
  font-src 'self' https://fonts.gstatic.com;
  img-src 'self' data: https:;
  connect-src 'self' https://api.yourdomain.com;
"
/>

πŸ“Š Monitoring & Analytics

Performance Metrics

// Custom performance tracking
export const trackPageLoad = (pageName: string) => {
  const navigation = performance.getEntriesByType(
    "navigation"
  )[0] as PerformanceNavigationTiming;

  const metrics = {
    pageName,
    loadTime: navigation.loadEventEnd - navigation.fetchStart,
    domContentLoaded:
      navigation.domContentLoadedEventEnd - navigation.fetchStart,
    firstPaint: performance.getEntriesByName("first-paint")[0]?.startTime,
    firstContentfulPaint: performance.getEntriesByName(
      "first-contentful-paint"
    )[0]?.startTime,
  };

  // Send to analytics service
  analytics.track("page_performance", metrics);
};

Error Reporting

// Centralized error reporting
export const reportError = (error: Error, context?: Record<string, any>) => {
  const errorReport = {
    message: error.message,
    stack: error.stack,
    timestamp: new Date().toISOString(),
    url: window.location.href,
    userAgent: navigator.userAgent,
    context,
  };

  // Send to error reporting service (Sentry, LogRocket, etc.)
  if (import.meta.env.PROD) {
    errorReportingService.captureException(error, errorReport);
  } else {
    console.error("Error Report:", errorReport);
  }
};

🚒 Deployment

Build Process

# Production build with optimizations
npm run build

# Analyze bundle size
npm run build -- --analyze

# Build with specific environment
VITE_APP_ENV=staging npm run build

Docker Deployment

# Multi-stage Dockerfile for optimized builds
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

CI/CD Pipeline

# GitHub Actions example
name: CI/CD Pipeline
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "18"
          cache: "npm"
      - run: npm ci
      - run: npm run lint
      - run: npm run type-check
      - run: npm run test
      - run: npm run build

🀝 Contributing

Development Workflow

  1. Fork & Clone: Fork the repository and clone your fork
  2. Branch: Create a feature branch (git checkout -b feature/amazing-feature)
  3. Code: Write your code following the project conventions
  4. Test: Ensure all tests pass (npm run test)
  5. Commit: Use conventional commits (feat:, fix:, docs:, etc.)
  6. Push: Push to your fork (git push origin feature/amazing-feature)
  7. PR: Open a pull request with a clear description

Code Standards

  • TypeScript: Use strict typing, avoid any
  • Components: Follow React functional component patterns
  • Styling: Use Tailwind classes, avoid inline styles
  • Naming: Use descriptive names, follow camelCase/PascalCase conventions
  • Documentation: Add JSDoc comments for complex functions

Commit Convention

feat: add new authentication system
fix: resolve memory leak in useEffect
docs: update API documentation
style: format code with prettier
refactor: simplify user validation logic
test: add unit tests for utils
chore: update dependencies

πŸ“š Learning Resources

Documentation Links

Best Practices

πŸ“„ License

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

πŸ™ Acknowledgments

  • React team for the amazing framework
  • Vercel team for Vite and modern tooling
  • Tailwind Labs for the utility-first CSS framework
  • The open-source community for incredible tools and libraries

Built with ❀️ using cutting-edge web technologies

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published