# Web Flow Base Template - Cursor Rules
## Project Overview
This is a Next.js 14+ base template using App Router, TypeScript, Tailwind CSS, shadcn/ui, and Supabase. The template supports:
- 65% Landing pages/marketing sites
- 25% Web applications with backend and authentication
- 10% E-commerce sites
## Code Style & TypeScript
### TypeScript Standards
- Use TypeScript strict mode - always type function parameters, return types, and variables
- Prefer `interface` over `type` for object shapes, use `type` for unions, intersections, and utilities
- Use `Readonly<>` for props interfaces when appropriate
- Avoid `any` - use `unknown` if type is truly unknown, then narrow it
- Use proper generic types for reusable components and functions
### Naming Conventions
- Components: PascalCase (e.g., `UserProfile.tsx`)
- Files: Match component name or use kebab-case for utilities (e.g., `user-profile.tsx`, `api-utils.ts`)
- Functions: camelCase (e.g., `getUserData`)
- Constants: UPPER_SNAKE_CASE (e.g., `MAX_RETRIES`)
- Types/Interfaces: PascalCase (e.g., `UserData`, `ApiResponse`)
### Code Formatting
- Use 2 spaces for indentation
- Use single quotes for strings unless double quotes are needed
- Always use semicolons
- Maximum line length: 100 characters
- Use trailing commas in multi-line objects/arrays
## Next.js App Router Patterns
### Server vs Client Components
- Default to Server Components - use `'use client'` only when necessary (interactivity, hooks, browser APIs)
- Server Components: Data fetching, static content, SEO-critical content
- Client Components: Interactive UI, state management, event handlers, browser APIs
### File Structure
```
app/
(marketing)/ # Landing page routes (grouped)
page.tsx
about/
page.tsx
(app)/ # Web app routes (grouped, with auth)
dashboard/
page.tsx
api/ # API routes
users/
route.ts
layout.tsx # Root layout
page.tsx # Home page
globals.css # Global styles
```
### Route Handlers (API Routes)
- Use `route.ts` (not `route.js`) in `app/api/` directory
- Always export named functions: `GET`, `POST`, `PUT`, `DELETE`, etc.
- Use proper HTTP status codes
- Always handle errors with try-catch
- Return proper JSON responses with `Response.json()`
- Example structure:
```typescript
import { NextRequest } from 'next/server';
export async function GET(request: NextRequest) {
try {
// Implementation
return Response.json({ data: result }, { status: 200 });
} catch (error) {
return Response.json(
{ error: 'Error message' },
{ status: 500 }
);
}
}
```
## Component Architecture
### Component Organization
- Place reusable UI components in `components/ui/` (shadcn/ui components)
- Place feature-specific components in `components/` with descriptive folders
- Use composition over configuration
- Keep components small and focused (single responsibility)
### Component Patterns
- Use functional components with TypeScript
- Define props interfaces above the component
- Use default exports for page components, named exports for reusable components
- Extract complex logic into custom hooks (place in `hooks/` directory)
- Use React.memo() for expensive components that re-render frequently
### Example Component Structure
```typescript
interface ComponentProps {
title: string;
description?: string;
children: React.ReactNode;
}
export function Component({ title, description, children }: ComponentProps) {
return (
<div>
<h1>{title}</h1>
{description && <p>{description}</p>}
{children}
</div>
);
}
```
## Styling with Tailwind CSS
### Tailwind Best Practices
- Use utility classes directly in JSX - avoid custom CSS when possible
- Use `cn()` utility from `@/lib/utils` for conditional classes
- Follow mobile-first responsive design: base styles for mobile, then `md:`, `lg:`, `xl:` breakpoints
- Use design tokens from `globals.css` (colors, spacing, etc.)
- Prefer Tailwind's spacing scale over arbitrary values
### Responsive Design
- Mobile-first approach: design for mobile, then enhance for larger screens
- Common breakpoints: `sm:` (640px), `md:` (768px), `lg:` (1024px), `xl:` (1280px), `2xl:` (1536px)
- Test on multiple screen sizes
- Use `flex` and `grid` for layouts, not fixed widths
### Dark Mode
- Use CSS variables defined in `globals.css`
- Components automatically support dark mode via theme variables
- Test both light and dark modes
## shadcn/ui Components
### Usage Guidelines
- Use shadcn/ui components from `components/ui/` directory
- Customize components by editing them directly (they're in your codebase)
- Follow shadcn/ui patterns for composition
- Use Radix UI primitives when building custom components
### Common Components
- `Button` - Use variants: default, destructive, outline, secondary, ghost, link
- `Input` - Always pair with `Label` for accessibility
- `Card` - Use for content containers
- `Dialog` - For modals and overlays
- `Form` - Use with react-hook-form and zod validation
## Supabase Database Patterns
### Schema Conventions
- Table names: plural, snake_case (e.g., `user_profiles`, `order_items`)
- Column names: snake_case (e.g., `created_at`, `user_id`)
- Primary keys: Always use `id` as UUID (type `uuid`, default `gen_random_uuid()`)
- Timestamps: Always include `created_at` (default `now()`) and `updated_at` (default `now()`, trigger to update)
- Foreign keys: Name as `{referenced_table}_id` (e.g., `user_id`, `product_id`)
- Indexes: Create indexes on foreign keys and frequently queried columns
### Row Level Security (RLS)
- ALWAYS enable RLS on all tables: `ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;`
- Create policies for each operation (SELECT, INSERT, UPDATE, DELETE)
- Use `auth.uid()` for user-based access control
- Example policy pattern:
```sql
-- Allow users to read their own data
CREATE POLICY "Users can read own data"
ON user_profiles FOR SELECT
USING (auth.uid() = user_id);
-- Allow authenticated users to insert their own data
CREATE POLICY "Users can insert own data"
ON user_profiles FOR INSERT
WITH CHECK (auth.uid() = user_id);
```
### Migration Patterns
- Use Supabase migrations in `supabase/migrations/` directory
- Name migrations: `YYYYMMDDHHMMSS_description.sql`
- Always include rollback considerations
- Test migrations on local Supabase instance first
### Common Schema Patterns
#### User Authentication Table
```sql
CREATE TABLE user_profiles (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE UNIQUE NOT NULL,
email TEXT,
full_name TEXT,
avatar_url TEXT,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX idx_user_profiles_user_id ON user_profiles(user_id);
```
#### Timestamp Update Trigger
```sql
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_user_profiles_updated_at
BEFORE UPDATE ON user_profiles
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
```
### Supabase Client Usage
- Use `@/lib/supabase/client` for client-side operations
- Use `@/lib/supabase/server` for server-side operations (Server Components, API routes)
- Always handle errors from Supabase queries
- Use TypeScript types generated from Supabase schema when available
## Authentication Patterns
### Supabase Auth Integration
- Use Supabase Auth for authentication (not NextAuth.js)
- Server-side: Use `createServerClient` from `@supabase/ssr`
- Client-side: Use `createBrowserClient` from `@supabase/ssr`
- Protect routes using middleware or server component checks
- Store user session in cookies (handled by Supabase SSR)
### Protected Routes
- Use route groups `(app)/` for authenticated routes
- Check authentication in layout or middleware
- Redirect unauthenticated users to login page
- Example middleware pattern:
```typescript
import { createServerClient } from '@supabase/ssr';
import { NextResponse } from 'next/server';
export async function middleware(request: NextRequest) {
const supabase = createServerClient(/* ... */);
const { data: { user } } = await supabase.auth.getUser();
if (!user && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
```
## API Route Patterns
### Error Handling
- Always use try-catch blocks
- Return consistent error response format: `{ error: string, message?: string }`
- Use appropriate HTTP status codes (400, 401, 403, 404, 500)
- Log errors server-side but don't expose sensitive details to client
### Validation
- Validate all input data using Zod schemas
- Validate query parameters, request body, and path parameters
- Return 400 with validation errors if input is invalid
### Response Format
- Success: `Response.json({ data: result }, { status: 200 })`
- Error: `Response.json({ error: 'Error message' }, { status: 400 })`
- Use consistent response structure across all API routes
## Form Handling
### React Hook Form + Zod
- Use `react-hook-form` for form state management
- Use `zod` for schema validation
- Use `@hookform/resolvers/zod` to connect them
- Always provide proper error messages
- Use shadcn/ui Form components for consistent styling
### Example Form Pattern
```typescript
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
const formSchema = z.object({
email: z.string().email('Invalid email address'),
name: z.string().min(2, 'Name must be at least 2 characters'),
});
type FormValues = z.infer<typeof formSchema>;
export function MyForm() {
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
});
// Form implementation
}
```
## Performance Optimization
### Image Optimization
- Always use Next.js `Image` component, never `<img>` tag
- Provide `width` and `height` or use `fill` with relative container
- Use `priority` for above-the-fold images
- Use appropriate `sizes` prop for responsive images
### Code Splitting
- Use dynamic imports for heavy components: `const Component = dynamic(() => import('./Component'))`
- Lazy load components that aren't immediately visible
- Split large libraries into separate chunks
### Data Fetching
- Use Server Components for data fetching when possible
- Use `fetch` with proper caching strategies
- Implement loading states with `loading.tsx` files
- Use Suspense boundaries for async components
## Accessibility (a11y)
### Requirements
- All interactive elements must be keyboard accessible
- Use semantic HTML elements (`<nav>`, `<main>`, `<article>`, `<section>`, etc.)
- Provide ARIA labels when semantic HTML isn't sufficient
- Ensure proper heading hierarchy (h1 → h2 → h3)
- All images must have alt text (use empty string `alt=""` for decorative images)
- Form inputs must have associated labels
- Use sufficient color contrast (WCAG AA minimum)
### Focus Management
- Ensure visible focus indicators
- Manage focus in modals and dialogs
- Skip links for main content navigation
## Vercel Deployment
### Environment Variables
- Use `.env.local` for local development
- Use Vercel dashboard for production environment variables
- Never commit `.env.local` or `.env` files
- Prefix public variables with `NEXT_PUBLIC_` for client-side access
### Build Optimization
- Ensure `next build` completes without errors
- Optimize bundle size - check for unnecessary dependencies
- Use Edge Runtime for API routes when appropriate: `export const runtime = 'edge'`
- Configure proper caching headers in `vercel.json`
### Deployment Checklist
- All environment variables set in Vercel
- Database migrations run (if using Supabase)
- RLS policies configured
- Error tracking configured (if applicable)
- Analytics configured (if applicable)
## E-commerce Patterns
### Product Schema
- Products table with variants support
- Cart/checkout flow
- Order management
- Payment integration (Stripe recommended)
### Common E-commerce Features
- Product catalog with filtering
- Shopping cart (use cookies or database)
- Checkout process
- Order confirmation
- Order history
## Landing Page Patterns
### Common Sections
- Hero section with CTA
- Features/benefits section
- Testimonials/social proof
- Pricing (if applicable)
- Contact form
- Footer with links
### SEO Optimization
- Use proper meta tags in `metadata` export
- Implement Open Graph tags
- Use semantic HTML
- Optimize images with alt text
- Create sitemap.xml
- Use structured data (JSON-LD) when appropriate
## File Organization
### Directory Structure
```
app/ # Next.js App Router
(marketing)/ # Landing page routes
(app)/ # Web app routes (with auth)
api/ # API routes
components/ # React components
ui/ # shadcn/ui components
lib/ # Utilities and helpers
supabase/ # Supabase client setup
utils.ts # General utilities
hooks/ # Custom React hooks
public/ # Static assets
```
### Import Organization
- Group imports: external packages, internal modules, relative imports
- Use absolute imports with `@/` alias
- Example:
```typescript
import { useState } from 'react';
import { NextRequest } from 'next/server';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { createServerClient } from '@/lib/supabase/server';
```
## Error Handling
### Client-Side Errors
- Use error boundaries for React errors
- Display user-friendly error messages
- Log errors to error tracking service (if configured)
### Server-Side Errors
- Use `error.tsx` files for route-level error handling
- Always catch and handle async errors
- Return appropriate HTTP status codes
- Don't expose sensitive error details to client
## Testing Considerations
### Code Quality
- Write self-documenting code with clear variable/function names
- Add comments for complex logic only
- Keep functions small and focused
- Avoid deep nesting (max 3-4 levels)
## Common Patterns to Follow
1. **Data Fetching**: Prefer Server Components, use Client Components only when needed
2. **State Management**: Use React hooks (useState, useReducer) for local state, consider Zustand/Context for global state
3. **Styling**: Tailwind utilities first, custom CSS only when necessary
4. **Forms**: React Hook Form + Zod validation
5. **API Routes**: Consistent error handling and response format
6. **Database**: Always enable RLS, use proper indexes, follow naming conventions
7. **Authentication**: Supabase Auth with proper session management
## When in Doubt
- Follow Next.js 14+ App Router best practices
- Use TypeScript strictly - type everything
- Prioritize accessibility and performance
- Write maintainable, readable code
- Follow existing patterns in the codebase
- Check Next.js, React, and Supabase documentation
Workflows from the Neura Market marketplace related to this Cursor resource