A production-ready React + TypeScript frontend boilerplate featuring cutting-edge technologies and enterprise-grade architecture patterns.
- β‘ 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
- π 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
- π 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
- π‘οΈ 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
| 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 |
- Node.js >= 18.0.0
- npm >= 9.0.0 or yarn >= 1.22.0
- Git for version control
# 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
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 reportsrc/
βββ 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
components/
βββ ui/ # Base UI components (shadcn/ui)
β βββ Button/
β βββ Input/
β βββ Card/
β βββ ...
βββ common/ # Shared business components
β βββ Header/
β βββ Footer/
β βββ Layout/
β βββ ErrorBoundary/
βββ forms/ # Form-specific components
βββ ContactForm/
βββ LoginForm/
βββ ...
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;
}// Automatic theme detection with system preference
const { theme, setTheme, isDark } = useTheme();
// Available themes: 'light', 'dark', 'system'
setTheme("dark");// Tailwind CSS breakpoints
const breakpoints = {
sm: '640px', // Mobile landscape
md: '768px', // Tablet
lg: '1024px', # Desktop
xl: '1280px', # Large desktop
'2xl': '1536px' # Extra large desktop
};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=""// tsconfig.json highlights
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"paths": {
"@/*": ["./src/*"]
}
}
}// 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,
},
});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;
};// 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,
});// 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
});// 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,
}))
);// 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);
}// 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"],
},
},
},
},
});// 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);
});
});// 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");
});
});// 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}`);
}
});<!-- 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;
"
/>// 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);
};// 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);
}
};# 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# 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;"]# 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- Fork & Clone: Fork the repository and clone your fork
- Branch: Create a feature branch (
git checkout -b feature/amazing-feature) - Code: Write your code following the project conventions
- Test: Ensure all tests pass (
npm run test) - Commit: Use conventional commits (
feat:,fix:,docs:, etc.) - Push: Push to your fork (
git push origin feature/amazing-feature) - PR: Open a pull request with a clear description
- 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
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- React 19 Documentation
- TypeScript Handbook
- Vite Guide
- Tailwind CSS v4
- React Router v7
- shadcn/ui Components
This project is licensed under the MIT License - see the LICENSE file for details.
- 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