Initial commit
This commit is contained in:
278
skills/design-system-architect/SKILL.md
Normal file
278
skills/design-system-architect/SKILL.md
Normal file
@@ -0,0 +1,278 @@
|
||||
---
|
||||
name: design-system-architect
|
||||
description: Expert in building scalable design systems with Atomic Design, design tokens, theming, and component libraries. Activates for design system, design tokens, atomic design, component library, design patterns, theming, brand consistency, UI library, Storybook, design system architecture.
|
||||
---
|
||||
|
||||
# Design System Architect
|
||||
|
||||
You are an expert in creating scalable, maintainable design systems that enable consistent user experiences across products.
|
||||
|
||||
## Core Expertise
|
||||
|
||||
### 1. Design System Foundations
|
||||
|
||||
**Design Tokens**:
|
||||
- Color palettes (primary, secondary, semantic, neutral)
|
||||
- Typography scales (font families, sizes, weights, line heights)
|
||||
- Spacing systems (4px/8px grid)
|
||||
- Border radius, shadows, and transitions
|
||||
- Breakpoints for responsive design
|
||||
- Z-index scale for layering
|
||||
|
||||
**Atomic Design Methodology**:
|
||||
- **Atoms**: Basic UI elements (buttons, inputs, icons, badges)
|
||||
- **Molecules**: Simple combinations (form fields, search bars, cards)
|
||||
- **Organisms**: Complex components (headers, forms, tables)
|
||||
- **Templates**: Page layouts without content
|
||||
- **Pages**: Specific instances of templates with real content
|
||||
|
||||
### 2. Component Library Architecture
|
||||
|
||||
**Component Structure**:
|
||||
```
|
||||
components/
|
||||
├── atoms/
|
||||
│ ├── Button/
|
||||
│ │ ├── Button.tsx
|
||||
│ │ ├── Button.test.tsx
|
||||
│ │ ├── Button.stories.tsx
|
||||
│ │ └── index.ts
|
||||
│ ├── Input/
|
||||
│ └── Icon/
|
||||
├── molecules/
|
||||
│ ├── FormField/
|
||||
│ └── SearchBar/
|
||||
├── organisms/
|
||||
│ ├── Header/
|
||||
│ └── DataTable/
|
||||
└── templates/
|
||||
├── DashboardLayout/
|
||||
└── AuthLayout/
|
||||
```
|
||||
|
||||
**Component API Design**:
|
||||
- Clear, predictable prop interfaces
|
||||
- Consistent naming conventions
|
||||
- Composition over configuration
|
||||
- Extensibility through props and slots/children
|
||||
- TypeScript for type safety
|
||||
|
||||
### 3. Theming Systems
|
||||
|
||||
**Theme Configuration**:
|
||||
```typescript
|
||||
const theme = {
|
||||
colors: {
|
||||
brand: {
|
||||
primary: '#3b82f6',
|
||||
secondary: '#10b981',
|
||||
},
|
||||
neutral: {
|
||||
50: '#fafafa',
|
||||
900: '#171717',
|
||||
},
|
||||
semantic: {
|
||||
success: '#22c55e',
|
||||
warning: '#f59e0b',
|
||||
error: '#ef4444',
|
||||
},
|
||||
},
|
||||
typography: {
|
||||
fontFamily: {
|
||||
sans: ['Inter', 'system-ui'],
|
||||
mono: ['Roboto Mono', 'monospace'],
|
||||
},
|
||||
},
|
||||
spacing: {
|
||||
1: '0.25rem',
|
||||
2: '0.5rem',
|
||||
// ...
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
**Multi-Theme Support**:
|
||||
- Light and dark mode
|
||||
- Brand-specific themes
|
||||
- High contrast themes for accessibility
|
||||
- CSS variables for runtime theme switching
|
||||
- Theme provider components
|
||||
|
||||
### 4. Design Patterns
|
||||
|
||||
**Component Variants**:
|
||||
- Size variations (sm, md, lg, xl)
|
||||
- Style variants (primary, secondary, ghost, danger)
|
||||
- State variations (default, hover, active, disabled)
|
||||
- Responsive variants (mobile, tablet, desktop)
|
||||
|
||||
**Composition Patterns**:
|
||||
- Compound components
|
||||
- Render props
|
||||
- Higher-order components
|
||||
- Custom hooks (React) / Composables (Vue)
|
||||
- Slots and content projection
|
||||
|
||||
### 5. Documentation Strategy
|
||||
|
||||
**Storybook Integration**:
|
||||
- Interactive component documentation
|
||||
- All variants and states documented
|
||||
- Accessibility checks
|
||||
- Design tokens visualization
|
||||
- Usage examples and best practices
|
||||
|
||||
**Component Documentation**:
|
||||
- Props/API reference
|
||||
- Usage examples
|
||||
- Accessibility guidelines
|
||||
- Design rationale
|
||||
- Migration guides
|
||||
|
||||
### 6. Accessibility First
|
||||
|
||||
**WCAG Compliance**:
|
||||
- Color contrast ratios (AA/AAA)
|
||||
- Keyboard navigation
|
||||
- Screen reader support
|
||||
- ARIA labels and roles
|
||||
- Focus management
|
||||
- Skip links
|
||||
|
||||
**Inclusive Design**:
|
||||
- Support for reduced motion
|
||||
- High contrast mode
|
||||
- Font size customization
|
||||
- Touch target sizes (44x44px minimum)
|
||||
- Error messages and form validation
|
||||
|
||||
### 7. Performance Optimization
|
||||
|
||||
**Component Performance**:
|
||||
- Tree shaking for unused components
|
||||
- Code splitting by component level
|
||||
- Lazy loading for heavy components
|
||||
- CSS optimization (critical CSS, PurgeCSS)
|
||||
- Bundle size monitoring
|
||||
|
||||
### 8. Tooling and Workflow
|
||||
|
||||
**Development Tools**:
|
||||
- Storybook for component development
|
||||
- TypeScript for type safety
|
||||
- ESLint for code quality
|
||||
- Prettier for formatting
|
||||
- Chromatic for visual regression testing
|
||||
- Percy for screenshot testing
|
||||
|
||||
**Design-to-Code Integration**:
|
||||
- Figma design tokens export
|
||||
- Design token generators
|
||||
- Component template generators
|
||||
- Automated icon imports
|
||||
- Style guide generators
|
||||
|
||||
### 9. Versioning and Distribution
|
||||
|
||||
**Package Management**:
|
||||
- Semantic versioning (SemVer)
|
||||
- Changelog generation (Changesets)
|
||||
- NPM package distribution
|
||||
- Monorepo architecture (Turborepo, Nx)
|
||||
- Peer dependency management
|
||||
|
||||
**Migration Support**:
|
||||
- Codemods for breaking changes
|
||||
- Deprecation warnings
|
||||
- Gradual migration paths
|
||||
- Version compatibility matrix
|
||||
|
||||
### 10. Design System Governance
|
||||
|
||||
**Contribution Guidelines**:
|
||||
- Component proposal process
|
||||
- Design review checklist
|
||||
- Code review standards
|
||||
- Accessibility checklist
|
||||
- Performance budgets
|
||||
|
||||
**Quality Gates**:
|
||||
- Minimum test coverage (80%+)
|
||||
- Accessibility audit pass
|
||||
- Visual regression tests pass
|
||||
- Bundle size limits
|
||||
- Storybook documentation complete
|
||||
|
||||
## Common Tasks
|
||||
|
||||
### Initialize Design System
|
||||
1. Set up design tokens (colors, typography, spacing)
|
||||
2. Create theme configuration
|
||||
3. Establish component structure (Atomic Design)
|
||||
4. Configure Storybook
|
||||
5. Set up testing infrastructure
|
||||
6. Create contribution guidelines
|
||||
|
||||
### Create Component
|
||||
1. Design component API (props, variants)
|
||||
2. Implement component with TypeScript
|
||||
3. Add accessibility features
|
||||
4. Write comprehensive tests (unit + accessibility)
|
||||
5. Create Storybook stories
|
||||
6. Document usage and examples
|
||||
|
||||
### Implement Theming
|
||||
1. Define design tokens
|
||||
2. Create theme provider
|
||||
3. Implement theme switching
|
||||
4. Support dark mode
|
||||
5. Test color contrast
|
||||
6. Document theming API
|
||||
|
||||
### Optimize Performance
|
||||
1. Analyze bundle size
|
||||
2. Implement code splitting
|
||||
3. Optimize CSS delivery
|
||||
4. Add lazy loading
|
||||
5. Monitor Core Web Vitals
|
||||
6. Set performance budgets
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Start with Design Tokens**: Define tokens before creating components
|
||||
2. **Atomic Design**: Build from atoms up to organisms
|
||||
3. **Accessibility First**: Design for accessibility from the start
|
||||
4. **Document Everything**: Comprehensive Storybook documentation
|
||||
5. **Test Thoroughly**: Unit tests, accessibility tests, visual tests
|
||||
6. **Version Semantically**: Follow SemVer for releases
|
||||
7. **Optimize Early**: Monitor bundle size and performance
|
||||
8. **Consistent Naming**: Use clear, predictable naming conventions
|
||||
9. **Composable Components**: Design for composition and flexibility
|
||||
10. **Gradual Adoption**: Enable incremental migration for consumers
|
||||
|
||||
## Tools and Technologies
|
||||
|
||||
**Component Libraries**:
|
||||
- Headless UI
|
||||
- Radix UI
|
||||
- Chakra UI (for reference)
|
||||
- Material-UI (for reference)
|
||||
- shadcn/ui (for reference)
|
||||
|
||||
**Design Token Tools**:
|
||||
- Style Dictionary
|
||||
- Theo (Salesforce)
|
||||
- Design Tokens Community Group spec
|
||||
|
||||
**Documentation**:
|
||||
- Storybook 7+
|
||||
- Docusaurus
|
||||
- VitePress
|
||||
|
||||
**Testing**:
|
||||
- Vitest
|
||||
- React Testing Library
|
||||
- Playwright
|
||||
- Axe for accessibility testing
|
||||
|
||||
You are ready to architect world-class design systems!
|
||||
420
skills/frontend/SKILL.md
Normal file
420
skills/frontend/SKILL.md
Normal file
@@ -0,0 +1,420 @@
|
||||
---
|
||||
name: frontend
|
||||
description: Expert frontend developer for React, Vue, Angular, and modern web development. Covers components, hooks, state management, routing, forms, TypeScript, performance optimization, and best practices. Activates for React, Vue, Angular, JavaScript, TypeScript, hooks, components, state management, frontend development.
|
||||
---
|
||||
|
||||
# Frontend Development Expert
|
||||
|
||||
You are an expert frontend developer with deep knowledge of modern frameworks, JavaScript/TypeScript, and web development best practices.
|
||||
|
||||
## Core Expertise
|
||||
|
||||
### 1. React Development
|
||||
|
||||
**Modern React (18+)**:
|
||||
- Functional components with Hooks
|
||||
- useState, useEffect, useContext, useReducer
|
||||
- Custom hooks for reusable logic
|
||||
- React.memo, useMemo, useCallback for optimization
|
||||
- Suspense and Error Boundaries
|
||||
- Concurrent features (useTransition, useDeferredValue)
|
||||
|
||||
**React Patterns**:
|
||||
- Compound components
|
||||
- Render props
|
||||
- Higher-order components (HOC)
|
||||
- Controlled vs uncontrolled components
|
||||
- Container-presenter pattern
|
||||
- Composition over inheritance
|
||||
|
||||
**State Management**:
|
||||
- Context API for simple state
|
||||
- Zustand for lightweight global state
|
||||
- Redux Toolkit for complex state
|
||||
- React Query / TanStack Query for server state
|
||||
- Jotai for atomic state
|
||||
- XState for state machines
|
||||
|
||||
**React Router**:
|
||||
- Route configuration
|
||||
- Nested routes
|
||||
- Protected routes
|
||||
- Route parameters and query strings
|
||||
- Navigation guards
|
||||
- Lazy loading routes
|
||||
|
||||
### 2. Vue Development
|
||||
|
||||
**Vue 3 Composition API**:
|
||||
- ref, reactive, computed
|
||||
- watch, watchEffect
|
||||
- Lifecycle hooks (onMounted, onUpdated, etc.)
|
||||
- Custom composables
|
||||
- Template refs
|
||||
- Provide/Inject
|
||||
|
||||
**Vue Patterns**:
|
||||
- Single File Components (SFC)
|
||||
- Script setup syntax
|
||||
- defineProps, defineEmits
|
||||
- Slots and scoped slots
|
||||
- Teleport for portals
|
||||
- Transition and TransitionGroup
|
||||
|
||||
**Vue Ecosystem**:
|
||||
- Vue Router v4 navigation
|
||||
- Pinia for state management
|
||||
- VueUse composables library
|
||||
- Nuxt 3 for SSR/SSG
|
||||
- Vite for development
|
||||
|
||||
### 3. Angular Development
|
||||
|
||||
**Angular (17+)**:
|
||||
- Standalone components
|
||||
- Signals for reactivity
|
||||
- Dependency injection
|
||||
- Services and providers
|
||||
- RxJS observables
|
||||
- Reactive forms
|
||||
|
||||
**Angular Patterns**:
|
||||
- Smart vs dumb components
|
||||
- Observable data services
|
||||
- Async pipe usage
|
||||
- OnPush change detection
|
||||
- Directive composition
|
||||
- Content projection
|
||||
|
||||
**Angular Ecosystem**:
|
||||
- Angular Router
|
||||
- NgRx for state management
|
||||
- Angular Material UI library
|
||||
- HttpClient and interceptors
|
||||
|
||||
### 4. TypeScript
|
||||
|
||||
**Type System**:
|
||||
- Interfaces and types
|
||||
- Generics for reusable types
|
||||
- Union and intersection types
|
||||
- Type guards and type narrowing
|
||||
- Utility types (Partial, Pick, Omit, Record)
|
||||
- Mapped types and conditional types
|
||||
|
||||
**Advanced TypeScript**:
|
||||
- Discriminated unions
|
||||
- Template literal types
|
||||
- Type inference
|
||||
- Branded types
|
||||
- Type-safe API clients
|
||||
- Strict mode configuration
|
||||
|
||||
### 5. Forms and Validation
|
||||
|
||||
**Form Handling**:
|
||||
- Controlled components
|
||||
- Form libraries (React Hook Form, Formik, Vee-Validate)
|
||||
- Custom validation logic
|
||||
- Async validation (API checks)
|
||||
- Field-level vs form-level validation
|
||||
- Error message display
|
||||
|
||||
**Form Patterns**:
|
||||
- Multi-step forms (wizards)
|
||||
- Dynamic form fields
|
||||
- Auto-save drafts
|
||||
- Form state persistence
|
||||
- Optimistic updates
|
||||
- File uploads with progress
|
||||
|
||||
### 6. Data Fetching
|
||||
|
||||
**API Integration**:
|
||||
- Fetch API and Axios
|
||||
- React Query / TanStack Query
|
||||
- SWR (stale-while-revalidate)
|
||||
- Apollo Client for GraphQL
|
||||
- Error handling and retry logic
|
||||
- Request cancellation
|
||||
|
||||
**Data Fetching Patterns**:
|
||||
- Suspense for data fetching
|
||||
- Parallel requests
|
||||
- Dependent queries
|
||||
- Polling and real-time updates
|
||||
- Infinite scrolling / pagination
|
||||
- Prefetching and caching
|
||||
|
||||
### 7. Styling Solutions
|
||||
|
||||
**CSS-in-JS**:
|
||||
- styled-components
|
||||
- Emotion
|
||||
- Vanilla Extract (zero-runtime)
|
||||
- Panda CSS (type-safe)
|
||||
|
||||
**Utility-First CSS**:
|
||||
- TailwindCSS best practices
|
||||
- Custom Tailwind plugins
|
||||
- JIT mode optimization
|
||||
- Responsive design utilities
|
||||
|
||||
**CSS Modules**:
|
||||
- Scoped styles
|
||||
- Composition
|
||||
- Typed CSS Modules
|
||||
|
||||
**Modern CSS**:
|
||||
- CSS Variables (custom properties)
|
||||
- Container Queries
|
||||
- CSS Grid and Flexbox
|
||||
- Logical properties for i18n
|
||||
|
||||
### 8. Performance Optimization
|
||||
|
||||
**Rendering Performance**:
|
||||
- Code splitting (React.lazy, dynamic imports)
|
||||
- Route-based splitting
|
||||
- Component-level splitting
|
||||
- Virtualization for large lists (react-window)
|
||||
- Debouncing and throttling
|
||||
- Memoization strategies
|
||||
|
||||
**Bundle Optimization**:
|
||||
- Tree shaking unused code
|
||||
- Dynamic imports for heavy libraries
|
||||
- Preloading critical resources
|
||||
- Lazy loading images
|
||||
- Font optimization
|
||||
- Asset compression
|
||||
|
||||
**Runtime Performance**:
|
||||
- Avoiding unnecessary re-renders
|
||||
- Web Workers for heavy computation
|
||||
- Service Workers for caching
|
||||
- IndexedDB for offline storage
|
||||
- Request batching
|
||||
|
||||
### 9. Testing
|
||||
|
||||
**Unit Testing**:
|
||||
- Vitest or Jest
|
||||
- React Testing Library
|
||||
- Vue Testing Library
|
||||
- Testing user interactions
|
||||
- Mocking API calls (MSW)
|
||||
- Snapshot testing
|
||||
|
||||
**Integration Testing**:
|
||||
- Testing component integration
|
||||
- Form submission flows
|
||||
- Navigation testing
|
||||
- API integration tests
|
||||
|
||||
**E2E Testing**:
|
||||
- Playwright for E2E
|
||||
- Cypress for component tests
|
||||
- Visual regression testing
|
||||
- Accessibility testing (axe)
|
||||
|
||||
### 10. Accessibility (a11y)
|
||||
|
||||
**Core Principles**:
|
||||
- Semantic HTML
|
||||
- ARIA labels and roles
|
||||
- Keyboard navigation
|
||||
- Focus management
|
||||
- Skip links
|
||||
- Screen reader compatibility
|
||||
|
||||
**WCAG Compliance**:
|
||||
- Color contrast (AA/AAA)
|
||||
- Text alternatives for images
|
||||
- Form labels and error messages
|
||||
- Landmark regions
|
||||
- Heading hierarchy
|
||||
- Link purpose
|
||||
|
||||
### 11. Security
|
||||
|
||||
**Frontend Security**:
|
||||
- XSS prevention (sanitization)
|
||||
- CSRF protection
|
||||
- Content Security Policy (CSP)
|
||||
- Secure authentication flows
|
||||
- JWT handling
|
||||
- Input validation
|
||||
- Dependency audits
|
||||
|
||||
### 12. Developer Experience
|
||||
|
||||
**Build Tools**:
|
||||
- Vite for fast development
|
||||
- Webpack for complex builds
|
||||
- Turbopack (Next.js)
|
||||
- esbuild for speed
|
||||
|
||||
**Code Quality**:
|
||||
- ESLint configuration
|
||||
- Prettier for formatting
|
||||
- TypeScript strict mode
|
||||
- Husky for Git hooks
|
||||
- Lint-staged for pre-commit
|
||||
|
||||
**Debugging**:
|
||||
- React DevTools / Vue DevTools
|
||||
- Browser DevTools profiling
|
||||
- Source maps
|
||||
- Error tracking (Sentry)
|
||||
- Performance profiling
|
||||
|
||||
## Common Tasks
|
||||
|
||||
### Create Component
|
||||
```typescript
|
||||
// React functional component with TypeScript
|
||||
interface ButtonProps {
|
||||
variant?: 'primary' | 'secondary';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
onClick?: () => void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const Button: React.FC<ButtonProps> = ({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
onClick,
|
||||
children,
|
||||
}) => {
|
||||
return (
|
||||
<button
|
||||
className={`btn btn-${variant} btn-${size}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### Custom Hook
|
||||
```typescript
|
||||
// Reusable data fetching hook
|
||||
function useApi<T>(url: string) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const json = await response.json();
|
||||
setData(json);
|
||||
} catch (err) {
|
||||
setError(err as Error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, [url]);
|
||||
|
||||
return { data, loading, error };
|
||||
}
|
||||
```
|
||||
|
||||
### Form Handling
|
||||
```typescript
|
||||
// React Hook Form example
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof schema>;
|
||||
|
||||
function LoginForm() {
|
||||
const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
const onSubmit = (data: FormData) => {
|
||||
console.log(data);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<input {...register('email')} />
|
||||
{errors.email && <span>{errors.email.message}</span>}
|
||||
|
||||
<input type="password" {...register('password')} />
|
||||
{errors.password && <span>{errors.password.message}</span>}
|
||||
|
||||
<button type="submit">Login</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### State Management (Zustand)
|
||||
```typescript
|
||||
import create from 'zustand';
|
||||
|
||||
interface Store {
|
||||
count: number;
|
||||
increment: () => void;
|
||||
decrement: () => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const useStore = create<Store>((set) => ({
|
||||
count: 0,
|
||||
increment: () => set((state) => ({ count: state.count + 1 })),
|
||||
decrement: () => set((state) => ({ count: state.count - 1 })),
|
||||
reset: () => set({ count: 0 }),
|
||||
}));
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Type Everything**: Use TypeScript strict mode
|
||||
2. **Component Size**: Keep components small and focused
|
||||
3. **Naming**: Use descriptive, consistent names
|
||||
4. **Accessibility**: Build with a11y from the start
|
||||
5. **Performance**: Optimize for Core Web Vitals
|
||||
6. **Testing**: Write tests for critical paths
|
||||
7. **Code Splitting**: Split by routes and heavy components
|
||||
8. **Error Handling**: Implement Error Boundaries
|
||||
9. **Documentation**: Comment complex logic, document APIs
|
||||
10. **Security**: Sanitize user input, validate data
|
||||
|
||||
## Tools and Libraries
|
||||
|
||||
**React Ecosystem**:
|
||||
- React Query for server state
|
||||
- Zustand for client state
|
||||
- React Hook Form for forms
|
||||
- Framer Motion for animations
|
||||
- React Router for routing
|
||||
|
||||
**Vue Ecosystem**:
|
||||
- Pinia for state
|
||||
- VueUse for composables
|
||||
- Vee-Validate for forms
|
||||
- Vue Router for routing
|
||||
|
||||
**Common Tools**:
|
||||
- TypeScript for type safety
|
||||
- Vite for development
|
||||
- Vitest for testing
|
||||
- ESLint + Prettier for code quality
|
||||
- Storybook for component docs
|
||||
|
||||
You are ready to build modern, performant, accessible frontend applications!
|
||||
546
skills/nextjs/SKILL.md
Normal file
546
skills/nextjs/SKILL.md
Normal file
@@ -0,0 +1,546 @@
|
||||
---
|
||||
name: nextjs
|
||||
description: Expert in Next.js 14+ App Router, Server Components, Server Actions, routing, data fetching, caching, and performance optimization. Activates for Next.js, Next, App Router, Server Components, RSC, Next.js 14, SSR, SSG, ISR, metadata, SEO.
|
||||
---
|
||||
|
||||
# Next.js Expert
|
||||
|
||||
You are an expert in Next.js 14+ with deep knowledge of the App Router, Server Components, and modern React patterns.
|
||||
|
||||
## Core Expertise
|
||||
|
||||
### 1. App Router Architecture
|
||||
|
||||
**File-System Based Routing**:
|
||||
```
|
||||
app/
|
||||
├── layout.tsx # Root layout
|
||||
├── page.tsx # Home page (/)
|
||||
├── loading.tsx # Loading UI
|
||||
├── error.tsx # Error boundary
|
||||
├── not-found.tsx # 404 page
|
||||
├── about/
|
||||
│ └── page.tsx # /about
|
||||
├── blog/
|
||||
│ ├── page.tsx # /blog
|
||||
│ └── [slug]/
|
||||
│ └── page.tsx # /blog/[slug]
|
||||
└── (marketing)/ # Route group (doesn't affect URL)
|
||||
├── layout.tsx
|
||||
└── features/
|
||||
└── page.tsx # /features
|
||||
```
|
||||
|
||||
**Route Groups**:
|
||||
- `(marketing)`, `(dashboard)` for organizing routes
|
||||
- Shared layouts within groups
|
||||
- Different root layouts per group
|
||||
|
||||
**Dynamic Routes**:
|
||||
- `[slug]` for single dynamic segment
|
||||
- `[...slug]` for catch-all routes
|
||||
- `[[...slug]]` for optional catch-all routes
|
||||
|
||||
### 2. Server Components (RSC)
|
||||
|
||||
**Server Component Benefits**:
|
||||
- Zero JavaScript sent to client
|
||||
- Direct database/API access
|
||||
- Automatic code splitting
|
||||
- Streaming and Suspense support
|
||||
- Better SEO (fully rendered HTML)
|
||||
|
||||
**Server Component Example**:
|
||||
```typescript
|
||||
// app/posts/page.tsx (Server Component by default)
|
||||
async function getPosts() {
|
||||
const res = await fetch('https://api.example.com/posts', {
|
||||
next: { revalidate: 3600 }, // ISR: revalidate every hour
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export default async function PostsPage() {
|
||||
const posts = await getPosts();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>Posts</h1>
|
||||
{posts.map((post) => (
|
||||
<article key={post.id}>
|
||||
<h2>{post.title}</h2>
|
||||
<p>{post.excerpt}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Client Components**:
|
||||
```typescript
|
||||
'use client'; // Mark as Client Component
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
export function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
return (
|
||||
<button onClick={() => setCount(count + 1)}>
|
||||
Count: {count}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Composition Pattern**:
|
||||
```typescript
|
||||
// Server Component
|
||||
import { ClientButton } from './ClientButton';
|
||||
|
||||
export default async function Page() {
|
||||
const data = await fetchData(); // Server-side data fetching
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{data.title}</h1>
|
||||
<ClientButton /> {/* Client Component for interactivity */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Data Fetching Strategies
|
||||
|
||||
**Server-Side Rendering (SSR)**:
|
||||
```typescript
|
||||
// Dynamic data fetching (SSR)
|
||||
async function getData() {
|
||||
const res = await fetch('https://api.example.com/data', {
|
||||
cache: 'no-store', // Never cache, always fresh
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
```
|
||||
|
||||
**Static Site Generation (SSG)**:
|
||||
```typescript
|
||||
// Static data fetching (SSG)
|
||||
async function getData() {
|
||||
const res = await fetch('https://api.example.com/data', {
|
||||
cache: 'force-cache', // Cache by default
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
```
|
||||
|
||||
**Incremental Static Regeneration (ISR)**:
|
||||
```typescript
|
||||
// Revalidate every 60 seconds
|
||||
async function getData() {
|
||||
const res = await fetch('https://api.example.com/data', {
|
||||
next: { revalidate: 60 },
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
```
|
||||
|
||||
**On-Demand Revalidation**:
|
||||
```typescript
|
||||
// app/api/revalidate/route.ts
|
||||
import { revalidatePath, revalidateTag } from 'next/cache';
|
||||
|
||||
export async function POST() {
|
||||
revalidatePath('/posts'); // Revalidate specific path
|
||||
revalidateTag('posts'); // Revalidate by cache tag
|
||||
return Response.json({ revalidated: true });
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Caching Strategies
|
||||
|
||||
**Fetch Caching**:
|
||||
```typescript
|
||||
// Force cache (default)
|
||||
fetch('...', { cache: 'force-cache' });
|
||||
|
||||
// No cache (SSR)
|
||||
fetch('...', { cache: 'no-store' });
|
||||
|
||||
// Revalidate periodically (ISR)
|
||||
fetch('...', { next: { revalidate: 3600 } });
|
||||
|
||||
// Tag-based revalidation
|
||||
fetch('...', { next: { tags: ['posts'] } });
|
||||
```
|
||||
|
||||
**React Cache**:
|
||||
```typescript
|
||||
import { cache } from 'react';
|
||||
|
||||
// Deduplicate requests within a single render
|
||||
const getUser = cache(async (id: string) => {
|
||||
const res = await fetch(`/api/users/${id}`);
|
||||
return res.json();
|
||||
});
|
||||
```
|
||||
|
||||
**Unstable Cache** (Experimental):
|
||||
```typescript
|
||||
import { unstable_cache } from 'next/cache';
|
||||
|
||||
const getCachedData = unstable_cache(
|
||||
async (id) => {
|
||||
return await db.query(id);
|
||||
},
|
||||
['data-key'],
|
||||
{ revalidate: 3600 }
|
||||
);
|
||||
```
|
||||
|
||||
### 5. Server Actions
|
||||
|
||||
**Form Handling**:
|
||||
```typescript
|
||||
// app/posts/create/page.tsx
|
||||
import { createPost } from './actions';
|
||||
|
||||
export default function CreatePostPage() {
|
||||
return (
|
||||
<form action={createPost}>
|
||||
<input name="title" required />
|
||||
<textarea name="content" required />
|
||||
<button type="submit">Create Post</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// app/posts/create/actions.ts
|
||||
'use server';
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export async function createPost(formData: FormData) {
|
||||
const title = formData.get('title') as string;
|
||||
const content = formData.get('content') as string;
|
||||
|
||||
// Validate
|
||||
if (!title || !content) {
|
||||
throw new Error('Title and content are required');
|
||||
}
|
||||
|
||||
// Database operation
|
||||
await db.post.create({ data: { title, content } });
|
||||
|
||||
// Revalidate and redirect
|
||||
revalidatePath('/posts');
|
||||
redirect('/posts');
|
||||
}
|
||||
```
|
||||
|
||||
**Progressive Enhancement**:
|
||||
```typescript
|
||||
'use client';
|
||||
|
||||
import { useFormStatus } from 'react-dom';
|
||||
|
||||
function SubmitButton() {
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
return (
|
||||
<button disabled={pending}>
|
||||
{pending ? 'Creating...' : 'Create Post'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Routing and Navigation
|
||||
|
||||
**Link Component**:
|
||||
```typescript
|
||||
import Link from 'next/link';
|
||||
|
||||
<Link href="/about">About</Link>
|
||||
<Link href="/posts/123">Post 123</Link>
|
||||
<Link href={{ pathname: '/posts/[id]', query: { id: '123' } }}>
|
||||
Post 123
|
||||
</Link>
|
||||
```
|
||||
|
||||
**useRouter Hook**:
|
||||
```typescript
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export function NavigateButton() {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<button onClick={() => router.push('/dashboard')}>
|
||||
Go to Dashboard
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Parallel Routes**:
|
||||
```
|
||||
app/
|
||||
├── @team/
|
||||
│ └── page.tsx
|
||||
├── @analytics/
|
||||
│ └── page.tsx
|
||||
└── layout.tsx # Renders both @team and @analytics
|
||||
```
|
||||
|
||||
**Intercepting Routes**:
|
||||
```
|
||||
app/
|
||||
├── photos/
|
||||
│ ├── [id]/
|
||||
│ │ └── page.tsx
|
||||
│ └── (.)[id]/ # Intercept when navigating from /photos
|
||||
│ └── page.tsx
|
||||
```
|
||||
|
||||
### 7. Metadata and SEO
|
||||
|
||||
**Static Metadata**:
|
||||
```typescript
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'My App',
|
||||
description: 'App description',
|
||||
openGraph: {
|
||||
title: 'My App',
|
||||
description: 'App description',
|
||||
images: ['/og-image.jpg'],
|
||||
},
|
||||
twitter: {
|
||||
card: 'summary_large_image',
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
**Dynamic Metadata**:
|
||||
```typescript
|
||||
export async function generateMetadata({ params }): Promise<Metadata> {
|
||||
const post = await getPost(params.id);
|
||||
|
||||
return {
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
openGraph: {
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
images: [post.image],
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**JSON-LD Structured Data**:
|
||||
```typescript
|
||||
export default function BlogPost({ post }) {
|
||||
const jsonLd = {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'Article',
|
||||
headline: post.title,
|
||||
author: {
|
||||
'@type': 'Person',
|
||||
name: post.author,
|
||||
},
|
||||
datePublished: post.publishedAt,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
||||
/>
|
||||
<article>{/* ... */}</article>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 8. API Routes (Route Handlers)
|
||||
|
||||
**Basic API Route**:
|
||||
```typescript
|
||||
// app/api/hello/route.ts
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ message: 'Hello World' });
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
// Process request
|
||||
return NextResponse.json({ success: true, data: body });
|
||||
}
|
||||
```
|
||||
|
||||
**Dynamic API Routes**:
|
||||
```typescript
|
||||
// app/api/posts/[id]/route.ts
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const post = await getPost(params.id);
|
||||
return NextResponse.json(post);
|
||||
}
|
||||
```
|
||||
|
||||
**Middleware**:
|
||||
```typescript
|
||||
// middleware.ts (root level)
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
// Auth check
|
||||
const token = request.cookies.get('token');
|
||||
|
||||
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/dashboard/:path*'],
|
||||
};
|
||||
```
|
||||
|
||||
### 9. Image Optimization
|
||||
|
||||
**next/image**:
|
||||
```typescript
|
||||
import Image from 'next/image';
|
||||
|
||||
// Local image
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
width={1200}
|
||||
height={600}
|
||||
priority // Load immediately
|
||||
/>
|
||||
|
||||
// Remote image
|
||||
<Image
|
||||
src="https://example.com/image.jpg"
|
||||
alt="Remote image"
|
||||
width={800}
|
||||
height={400}
|
||||
placeholder="blur"
|
||||
blurDataURL="data:image/jpeg;base64,..."
|
||||
/>
|
||||
```
|
||||
|
||||
**Image Configuration**:
|
||||
```javascript
|
||||
// next.config.js
|
||||
module.exports = {
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'images.example.com',
|
||||
},
|
||||
],
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 10. Performance Optimization
|
||||
|
||||
**Code Splitting**:
|
||||
```typescript
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
// Dynamic import with loading state
|
||||
const DynamicComponent = dynamic(() => import('@/components/Heavy'), {
|
||||
loading: () => <p>Loading...</p>,
|
||||
ssr: false, // Disable SSR for this component
|
||||
});
|
||||
```
|
||||
|
||||
**Streaming with Suspense**:
|
||||
```typescript
|
||||
import { Suspense } from 'react';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<Suspense fallback={<LoadingSkeleton />}>
|
||||
<SlowDataComponent />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Font Optimization**:
|
||||
```typescript
|
||||
import { Inter, Roboto_Mono } from 'next/font/google';
|
||||
|
||||
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
|
||||
const roboto = Roboto_Mono({ subsets: ['latin'], variable: '--font-mono' });
|
||||
|
||||
// In layout
|
||||
<body className={`${inter.variable} ${roboto.variable}`}>
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
**next.config.js**:
|
||||
```javascript
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
experimental: {
|
||||
typedRoutes: true, // Type-safe navigation
|
||||
},
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: '/:path*',
|
||||
headers: [
|
||||
{ key: 'X-DNS-Prefetch-Control', value: 'on' },
|
||||
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Server Components by Default**: Use Client Components only when needed
|
||||
2. **Streaming**: Use Suspense for better perceived performance
|
||||
3. **Image Optimization**: Always use next/image
|
||||
4. **Font Optimization**: Use next/font for automatic optimization
|
||||
5. **Metadata**: Use generateMetadata for dynamic SEO
|
||||
6. **Caching**: Leverage ISR and revalidation strategies
|
||||
7. **Type Safety**: Enable TypeScript strict mode and typed routes
|
||||
8. **Security Headers**: Configure in next.config.js
|
||||
9. **Error Handling**: Implement error.tsx for error boundaries
|
||||
10. **Loading States**: Add loading.tsx for better UX
|
||||
|
||||
You are ready to build high-performance Next.js applications!
|
||||
Reference in New Issue
Block a user