vercel-development
Vercel and Next.js deployment best practices including server components, edge functions, AI SDK integration, and performance optimization.
What this skill does
# Vercel Development Best Practices
## Overview
This skill provides comprehensive guidelines for developing and deploying applications on Vercel, with a focus on Next.js, React Server Components, Edge Functions, and the Vercel AI SDK.
## Core Principles
- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC)
- Implement responsive design with Tailwind CSS using mobile-first approach
- Optimize for Core Web Vitals and performance
## Project Structure
```
my-app/
├── app/ # App Router pages and layouts
│ ├── (auth)/ # Route groups
│ ├── api/ # API routes
│ ├── layout.tsx # Root layout
│ └── page.tsx # Home page
├── components/ # React components
│ ├── ui/ # UI primitives
│ └── features/ # Feature components
├── lib/ # Utility functions
├── hooks/ # Custom React hooks
├── types/ # TypeScript types
├── public/ # Static assets
└── vercel.json # Vercel configuration
```
## Next.js App Router Guidelines
### File Naming Conventions
- Use lowercase with dashes for directories (e.g., `components/auth-wizard`)
- Prefer named exports for components and functions
- Use `page.tsx` for route pages, `layout.tsx` for layouts
- Use `loading.tsx` for loading states, `error.tsx` for error boundaries
### Server Components (Default)
```typescript
// app/users/page.tsx
import { getUsers } from '@/lib/data';
export default async function UsersPage() {
const users = await getUsers();
return (
<main>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</main>
);
}
```
### Client Components (When Needed)
```typescript
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
```
## TypeScript Standards
### Type Definitions
```typescript
// Use interfaces over types for object shapes
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
}
// Use types for unions and complex types
type Status = 'pending' | 'active' | 'inactive';
// Avoid enums; use const objects instead
const STATUS = {
PENDING: 'pending',
ACTIVE: 'active',
INACTIVE: 'inactive',
} as const;
type StatusValue = typeof STATUS[keyof typeof STATUS];
```
### Component Props
```typescript
interface ButtonProps {
children: React.ReactNode;
variant?: 'primary' | 'secondary' | 'ghost';
size?: 'sm' | 'md' | 'lg';
disabled?: boolean;
onClick?: () => void;
}
export function Button({
children,
variant = 'primary',
size = 'md',
disabled = false,
onClick,
}: ButtonProps) {
// Implementation
}
```
## API Routes
### Route Handlers
```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
const CreateUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
});
export async function GET(request: NextRequest) {
const users = await getUsers();
return NextResponse.json(users);
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const validated = CreateUserSchema.parse(body);
const user = await createUser(validated);
return NextResponse.json(user, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Validation failed', details: error.errors },
{ status: 400 }
);
}
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
### Edge Runtime
```typescript
// app/api/edge-function/route.ts
export const runtime = 'edge';
export async function GET(request: Request) {
return new Response(JSON.stringify({ message: 'Hello from the edge!' }), {
headers: { 'Content-Type': 'application/json' },
});
}
```
## Vercel AI SDK Integration
### Streaming Chat UI
```typescript
'use client';
import { useChat } from 'ai/react';
export function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: '/api/chat',
});
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto">
{messages.map(message => (
<div key={message.id} className={message.role === 'user' ? 'text-right' : ''}>
<p>{message.content}</p>
</div>
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={handleInputChange}
placeholder="Type a message..."
disabled={isLoading}
/>
</form>
</div>
);
}
```
### AI API Route
```typescript
// app/api/chat/route.ts
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
export async function POST(request: Request) {
const { messages } = await request.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
system: 'You are a helpful assistant.',
});
return result.toDataStreamResponse();
}
```
### Error Handling for AI
```typescript
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
export async function POST(request: Request) {
try {
const { messages } = await request.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
});
return result.toDataStreamResponse();
} catch (error) {
// Handle rate limiting
if (error.message?.includes('rate limit')) {
return new Response('Rate limit exceeded. Please try again later.', {
status: 429,
});
}
// Handle quota exceeded
if (error.message?.includes('quota')) {
return new Response('API quota exceeded.', { status: 402 });
}
// Fallback to alternative model
console.error('Primary model failed:', error);
return new Response('Service temporarily unavailable.', { status: 503 });
}
}
```
## Data Fetching
### Server-Side Data Fetching
```typescript
// Fetch data in Server Components
async function getData() {
const res = await fetch('https://api.example.com/data', {
next: { revalidate: 3600 }, // Cache for 1 hour
});
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function Page() {
const data = await getData();
return <div>{/* Render data */}</div>;
}
```
### URL State Management
```typescript
// Use URL query parameters for server state
import { useSearchParams, useRouter } from 'next/navigation';
export function Filters() {
const searchParams = useSearchParams();
const router = useRouter();
const updateFilter = (key: string, value: string) => {
const params = new URLSearchParams(searchParams);
params.set(key, value);
router.push(`?${params.toString()}`);
};
return (/* Filter UI */);
}
```
## Performance Optimization
### Image Optimization
```typescript
import Image from 'next/image';
export function Hero() {
return (
<Image
src="/hero.jpg"
alt="Hero image"
width={1200}
height={600}
priority // Load immediately for LCP
placeholder="blur"
blurDataURL="data:image/jpeg;base64,..."
/>
);
}
```
### Dynamic Imports
```typescript
import dynamic from 'next/dynamic';
// Lazy load heavy components
const HeavyChart = dynamic(() => import('@/components/heavy-chart'), {
loading: () => <div>Loading chart...</div>,
ssr: false, // Disable SSR if needed
});
```
### Suspense Boundaries
```typescript
import { Suspense } from 'react';
export default Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.