Best Practices for ContextWeave Development in Bolt.new

This guide outlines best practices for developing, maintaining, and deploying ContextWeave using Bolt.new, ensuring optimal performance, security, and maintainability.

Development Best Practices

1. Code Organization

// ✅ Good: Clear file structure components/ ├── ui/ # Reusable UI components │ ├── Button.tsx │ ├── Card.tsx │ └── Input.tsx ├── features/ # Feature-specific components │ ├── ContextGenerator.tsx │ ├── LibrarySearch.tsx │ └── ProfileBuilder.tsx └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Navigation.tsx // ✅ Good: Consistent naming // Use PascalCase for components export function ContextGenerator() {} // Use camelCase for functions and variables const generateContext = async () => {} // Use UPPER_CASE for constants const API_ENDPOINTS = { GENERATE: '/api/generate-context', SEARCH: '/api/search-libraries' }

2. TypeScript Best Practices

// ✅ Good: Define interfaces for all data structures interface LibraryInfo { name: string ecosystem: string version: string description?: string repository_url?: string } interface ContextResult { content: string sources: Source[] processing_time: number library_info: LibraryInfo } // ✅ Good: Use proper error handling with types type ApiResponse<T> = { success: true data: T } | { success: false error: string } const fetchLibraries = async (query: string): Promise<ApiResponse<LibraryInfo[]>> => { try { const response = await fetch(`/api/search?q=${query}`) const data = await response.json() return { success: true, data } } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Unknown error' } } } // ✅ Good: Use generic types for reusable components interface ButtonProps<T = HTMLButtonElement> { children: React.ReactNode onClick?: (event: React.MouseEvent<T>) => void disabled?: boolean variant?: 'primary' | 'secondary' | 'outline' } export function Button<T = HTMLButtonElement>({ children, onClick, disabled, variant = 'primary' }: ButtonProps<T>) { return ( <button onClick={onClick} disabled={disabled} className={`btn btn-${variant}`} > {children} </button> ) }

3. React Best Practices

// ✅ Good: Use proper hooks and state management import { useState, useEffect, useCallback, useMemo } from 'react' export function ContextGenerator() { const [query, setQuery] = useState('') const [result, setResult] = useState<ContextResult | null>(null) const [loading, setLoading] = useState(false) // ✅ Good: Memoize expensive calculations const processedResult = useMemo(() => { if (!result) return null return { ...result, wordCount: result.content.split(' ').length, readingTime: Math.ceil(result.content.split(' ').length / 200) } }, [result]) // ✅ Good: Use useCallback for event handlers const handleGenerate = useCallback(async () => { if (!query.trim()) return setLoading(true) try { const response = await fetch('/api/generate-context', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } const data = await response.json() setResult(data) } catch (error) { console.error('Generation failed:', error) // Handle error appropriately } finally { setLoading(false) } }, [query]) // ✅ Good: Cleanup effects useEffect(() => { const controller = new AbortController() const fetchData = async () => { try { const response = await fetch('/api/data', { signal: controller.signal }) // Handle response } catch (error) { if (error.name !== 'AbortError') { console.error('Fetch failed:', error) } } } fetchData() return () => { controller.abort() } }, []) return ( <div> {/* Component JSX */} </div> ) } // ❌ Bad: Don't use inline objects in JSX <Component style={{ marginTop: 10 }} /> // Creates new object on every render // ✅ Good: Define styles outside or use CSS classes const styles = { marginTop: 10 } <Component style={styles} /> // or <Component className="mt-2" />

4. API Route Best Practices

// ✅ Good: Proper API route structure import { NextRequest, NextResponse } from 'next/server' import { z } from 'zod' // Define request schema const GenerateContextSchema = z.object({ library: z.string().min(1), version: z.string().optional(), context: z.string().min(1), ecosystem: z.string().optional() }) export async function POST(request: NextRequest) { try { // Validate request body const body = await request.json() const validatedData = GenerateContextSchema.parse(body) // Add rate limiting (in production) const clientIP = request.ip || 'unknown' await checkRateLimit(clientIP) // Process request const result = await generateContext(validatedData) // Return structured response return NextResponse.json({ success: true, data: result, timestamp: new Date().toISOString() }) } catch (error) { console.error('API Error:', error) if (error instanceof z.ZodError) { return NextResponse.json( { success: false, error: 'Invalid request data', details: error.errors }, { status: 400 } ) } if (error instanceof RateLimitError) { return NextResponse.json( { success: false, error: 'Rate limit exceeded' }, { status: 429 } ) } return NextResponse.json( { success: false, error: 'Internal server error' }, { status: 500 } ) } } // ✅ Good: Add CORS headers export async function OPTIONS(request: NextRequest) { return new NextResponse(null, { status: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, }) }

Performance Best Practices

1. Optimization Techniques

// ✅ Good: Use dynamic imports for code splitting import dynamic from 'next/dynamic' const HeavyComponent = dynamic(() => import('./HeavyComponent'), { loading: () => <div>Loading...</div>, ssr: false // If component doesn't need SSR }) // ✅ Good: Optimize images import Image from 'next/image' export function OptimizedImage() { return ( <Image src="/hero-image.jpg" alt="Hero image" width={800} height={600} priority // For above-the-fold images placeholder="blur" blurDataURL="data:image/jpeg;base64,..." /> ) } // ✅ Good: Use proper caching export const revalidate = 3600 // Cache for 1 hour export async function generateStaticParams() { // Pre-generate common library pages return [ { library: 'react' }, { library: 'next' }, { library: 'express' } ] }

2. Database Optimization

-- ✅ Good: Add proper indexes CREATE INDEX CONCURRENTLY idx_profiles_user_id ON profiles(user_id); CREATE INDEX CONCURRENTLY idx_generations_user_created ON generations(user_id, created_at DESC); CREATE INDEX CONCURRENTLY idx_libraries_ecosystem_name ON libraries(ecosystem, name); -- ✅ Good: Use efficient queries -- Instead of SELECT * SELECT id, name, description FROM libraries WHERE ecosystem = 'npm'; -- Use LIMIT for pagination SELECT * FROM generations WHERE user_id = $1 ORDER BY created_at DESC LIMIT 20 OFFSET $2;

3. Caching Strategy

// ✅ Good: Implement multi-level caching import { unstable_cache } from 'next/cache' // Cache expensive operations export const getCachedLibraryInfo = unstable_cache( async (library: string, version: string) => { const result = await fetchLibraryInfo(library, version) return result }, ['library-info'], { revalidate: 3600, // 1 hour tags: ['library-info'] } ) // Client-side caching with React Query (if using) import { useQuery } from '@tanstack/react-query' export function useLibraryInfo(library: string) { return useQuery({ queryKey: ['library', library], queryFn: () => fetchLibraryInfo(library), staleTime: 5 * 60 * 1000, // 5 minutes cacheTime: 10 * 60 * 1000, // 10 minutes }) }

Security Best Practices

1. Environment Variables

# ✅ Good: Proper environment variable naming # Public variables (accessible in browser) NEXT_PUBLIC_SUPABASE_URL=https://project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... # Private variables (server-side only) SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... OPENAI_API_KEY=sk-... GOOGLE_API_KEY=AIza... # ❌ Bad: Don't expose sensitive keys to client # NEXT_PUBLIC_OPENAI_API_KEY=sk-... // Never do this!

2. Input Validation

// ✅ Good: Validate all inputs import { z } from 'zod' const UserInputSchema = z.object({ query: z.string() .min(1, 'Query is required') .max(1000, 'Query too long') .regex(/^[a-zA-Z0-9\s\-_.]+$/, 'Invalid characters'), library: z.string() .min(1, 'Library is required') .max(100, 'Library name too long'), ecosystem: z.enum(['npm', 'pypi', 'github']).optional() }) // ✅ Good: Sanitize HTML content import DOMPurify from 'isomorphic-dompurify' const sanitizeHtml = (html: string) => { return DOMPurify.sanitize(html, { ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre'], ALLOWED_ATTR: [] }) }

3. Authentication & Authorization

// ✅ Good: Proper auth checks import { createServerComponentClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' export async function getServerSideProps() { const supabase = createServerComponentClient({ cookies }) const { data: { session } } = await supabase.auth.getSession() if (!session) { return { redirect: { destination: '/login', permanent: false, }, } } return { props: { user: session.user, }, } } // ✅ Good: Row Level Security policies -- Only allow users to access their own data CREATE POLICY "Users can only access own data" ON profiles FOR ALL USING (auth.uid() = user_id); -- Allow public read access to libraries CREATE POLICY "Public read access" ON libraries FOR SELECT TO anon, authenticated USING (true);

Testing Best Practices

1. Unit Testing

// ✅ Good: Test utilities and pure functions import { describe, it, expect } from 'vitest' import { calculateReadingTime, formatLibraryName } from '@/lib/utils' describe('Utils', () => { describe('calculateReadingTime', () => { it('should calculate reading time correctly', () => { const text = 'word '.repeat(200) // 200 words expect(calculateReadingTime(text)).toBe(1) // 1 minute }) it('should handle empty text', () => { expect(calculateReadingTime('')).toBe(0) }) }) describe('formatLibraryName', () => { it('should format npm packages correctly', () => { expect(formatLibraryName('react', 'npm')).toBe('react (npm)') }) }) })

2. Integration Testing

// ✅ Good: Test API routes import { describe, it, expect } from 'vitest' import { POST } from '@/app/api/generate-context/route' describe('/api/generate-context', () => { it('should generate context successfully', async () => { const request = new Request('http://localhost:3000/api/generate-context', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ library: 'react', context: 'Create a component with hooks' }) }) const response = await POST(request) const data = await response.json() expect(response.status).toBe(200) expect(data.success).toBe(true) expect(data.data.content).toBeDefined() }) it('should handle invalid input', async () => { const request = new Request('http://localhost:3000/api/generate-context', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) // Missing required fields }) const response = await POST(request) expect(response.status).toBe(400) }) })

3. E2E Testing

// ✅ Good: Test critical user flows import { test, expect } from '@playwright/test' test.describe('ContextWeave App', () => { test('should generate context successfully', async ({ page }) => { await page.goto('/') // Navigate to playground await page.click('text=Try the Playground') await expect(page).toHaveURL('/playground') // Select example await page.click('button:has-text("Stream OpenAI")') // Generate context await page.click('button:has-text("Generate Context")') // Wait for results await expect(page.locator('[data-testid="generated-context"]')).toBeVisible() // Verify content const content = await page.locator('[data-testid="generated-context"]').textContent() expect(content).toContain('react') }) })

Deployment Best Practices

1. Build Optimization

// ✅ Good: Optimize Next.js config /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, }, // Optimize images images: { domains: ['images.unsplash.com'], formats: ['image/webp', 'image/avif'], }, // Compress responses compress: true, // Enable SWC minification swcMinify: true, // Bundle analyzer (development only) ...(process.env.ANALYZE === 'true' && { webpack: (config) => { config.plugins.push(new BundleAnalyzerPlugin()) return config }, }), } module.exports = nextConfig

2. Environment Configuration

# ✅ Good: Environment-specific configurations # Development NODE_ENV=development NEXT_TELEMETRY_DISABLED=1 # Staging NODE_ENV=production NEXT_PUBLIC_SUPABASE_URL=https://staging-project.supabase.co # Production NODE_ENV=production NEXT_PUBLIC_SUPABASE_URL=https://prod-project.supabase.co

3. Monitoring and Logging

// ✅ Good: Structured logging import { logger } from '@/lib/logger' export async function POST(request: NextRequest) { const startTime = Date.now() try { const body = await request.json() logger.info('API request started', { endpoint: '/api/generate-context', library: body.library, userAgent: request.headers.get('user-agent'), }) const result = await generateContext(body) logger.info('API request completed', { endpoint: '/api/generate-context', duration: Date.now() - startTime, success: true, }) return NextResponse.json({ success: true, data: result }) } catch (error) { logger.error('API request failed', { endpoint: '/api/generate-context', duration: Date.now() - startTime, error: error.message, stack: error.stack, }) return NextResponse.json( { success: false, error: 'Internal server error' }, { status: 500 } ) } }

Maintenance Best Practices

1. Regular Updates

# ✅ Good: Regular maintenance schedule # Weekly npm audit npm outdated npm run lint npm run type-check npm run test # Monthly npm update # Review and update dependencies # Check for security vulnerabilities # Performance audit # Quarterly # Major version updates # Architecture review # Security audit

2. Code Quality

// ✅ Good: ESLint configuration { "extends": [ "next/core-web-vitals", "@typescript-eslint/recommended", "prettier" ], "rules": { "@typescript-eslint/no-unused-vars": "error", "@typescript-eslint/no-explicit-any": "warn", "prefer-const": "error", "no-console": "warn" } }

3. Documentation

// ✅ Good: Document complex functions /** * Generates context-aware documentation for a library * * @param library - The library name (e.g., 'react', 'express') * @param version - The library version (e.g., '18.2.0', 'latest') * @param context - User's specific use case or question * @param options - Additional options for generation * @returns Promise resolving to generated context with metadata * * @example * ```typescript * const result = await generateContext('react', '18.2.0', 'Create a form component') * console.log(result.content) // Generated documentation * ``` */ export async function generateContext( library: string, version: string, context: string, options: GenerationOptions = {} ): Promise<ContextResult> { // Implementation }

Bolt.new Specific Best Practices

1. Working with AI Assistant

# ✅ Good: How to interact with Claude in Bolt.new # Be specific with requests "Add error handling to the generateContext function in lib/api-clients.ts" # Provide context "I'm getting a TypeScript error in components/ContextGenerator.tsx on line 45. The error is 'Property does not exist on type'. Here's the relevant code: [paste code]" # Ask for explanations "Explain how the caching strategy works in this application" # Request best practices "What's the best way to handle API rate limiting in this Next.js app?"

2. File Management

# ✅ Good: Keep files organized # Use the file explorer efficiently # Group related files in folders # Use descriptive file names # Keep components under 200 lines when possible

3. Version Control

# ✅ Good: Use Git effectively in Bolt.new # Commit frequently with descriptive messages git commit -m "feat: add context generation with error handling" git commit -m "fix: resolve TypeScript errors in ContextGenerator" git commit -m "docs: update API documentation" # Use conventional commit format # feat: new feature # fix: bug fix # docs: documentation # style: formatting # refactor: code restructuring # test: adding tests

Following these best practices ensures ContextWeave remains maintainable, performant, and secure throughout its development lifecycle in Bolt.new.