Skip to main content
skill CX Codex

vercel-reference-architecture — Claude Code skill: setup guide

vercel-reference-architecture sets up a layered Vercel architecture for Next.js applications. Helps structure edge middleware, serverless API routes, and environment validation.

MIT 1 installs ★ 2,935 updated 2026-11-01

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add jeremylongshore/tons-of-skills-marketplace --skill vercel-reference-architecture -a claude-code
Open on GitHub

What vercel-reference-architecture does

This skill implements a standardized layout for modern Vercel projects. It targets Next.js 14+ with TypeScript. The pattern divides code between App Router directories, shared utilities, and Edge Middleware. The assistant inspects and edits project files using Read, Write, Edit, and Grep.

Inside, environment variables are verified at startup via Zod in src/lib/env.ts. Missing variables trigger immediate startup errors. The skill also provisions a lazy singleton for PrismaClient in src/lib/db.ts to reduce cold starts, an Edge Middleware for session cookie redirects, and an /api/health status check.

The reference setup relies strictly on TypeScript, Prisma, and Zod. Different tools require manual rewrites.

What it helps with

  • structure Next.js App Router directories across edge and serverless boundaries
  • validate environment variables during startup using Zod schemas
  • prevent duplicate Prisma connection pools during development hot reloads
  • set up Edge Middleware to safeguard routes with session cookies

Example prompts for the agent

  • Organize this Next.js project using the Vercel reference architecture
  • Set up environment variable validation with Zod in src/lib/env.ts
  • Add Edge Middleware to protect dashboard routes using session cookies

How to install vercel-reference-architecture

1Skills CLI (Vercel)

npx skills add jeremylongshore/tons-of-skills-marketplace --skill vercel-reference-architecture -a claude-code

2Manually: put the files in place

~/.claude/skills/vercel-reference-architecture/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/vercel-reference-architecture/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about vercel-reference-architecture

How to install vercel-reference-architecture in Claude Code?

Run npx skills add jeremylongshore/tons-of-skills-marketplace --skill vercel-reference-architecture -a claude-code. The file is saved directly to ~/.claude/skills/vercel-reference-architecture/SKILL.md.

What does vercel-reference-architecture do?

It equips the agent with guidelines to build or refactor Vercel projects. This covers folder separation, cache headers on API handlers, database singletons, and security headers in vercel.json.

What stack requirements does this architecture have?

The setup expects Next.js 14+ and TypeScript. Its sample implementations also rely on Prisma as the database client and Zod for schema parsing.

Source text

SKILL.md · MIT
---
name: vercel-reference-architecture
description: 'Implement a Vercel reference architecture with layered project structure
  and best practices.

  Use when designing new Vercel projects, reviewing project structure,

  or establishing architecture standards for Vercel applications.

  Trigger with phrases like "vercel architecture", "vercel project structure",

  "vercel best practices layout", "how to organize vercel project".

  '
allowed-tools: Read, Write, Edit, Grep
version: 1.18.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
- saas
- vercel
- architecture
- best-practices
compatibility: Designed for Claude Code
---
# Vercel Reference Architecture

## Overview

Implement a production-ready Vercel project architecture with clear separation across edge, server, and client layers. Covers directory structure, middleware patterns, API route organization, shared utilities, and configuration management.

## Prerequisites

- Understanding of Vercel's deployment model (edge, serverless, static)
- TypeScript project setup
- Next.js 14+ (recommended) or other Vercel-supported framework

## Instructions

### Step 1: Directory Structure

```
my-vercel-app/
├── public/                    # Static assets (served from CDN)
│   ├── favicon.ico
│   └── images/
├── src/
│   ├── app/                   # Next.js App Router pages
│   │   ├── layout.tsx         # Root layout
│   │   ├── page.tsx           # Home page
│   │   ├── api/               # API routes (serverless functions)
│   │   │   ├── health/route.ts
│   │   │   ├── users/route.ts
│   │   │   └── webhooks/
│   │   │       └── vercel/route.ts
│   │   ├── dashboard/         # Protected pages
│   │   │   ├── layout.tsx
│   │   │   └── page.tsx
│   │   └── (marketing)/       # Public pages (route group)
│   │       ├── pricing/page.tsx
│   │       └── about/page.tsx
│   ├── lib/                   # Shared utilities (server + client)
│   │   ├── api-client.ts      # External API wrapper
│   │   ├── db.ts              # Database client (lazy singleton)
│   │   ├── env.ts             # Typed environment variables
│   │   └── errors.ts          # Error classes
│   ├── components/            # React components
│   │   ├── ui/                # Design system primitives
│   │   └── features/          # Feature-specific components
│   └── middleware.ts          # Edge Middleware (auth, redirects)
├── vercel.json                # Vercel configuration
├── next.config.js             # Next.js configuration
├── tsconfig.json
├── package.json
└── .env.example               # Required env vars (no values)
```

### Step 2: Typed Environment Variables

```typescript
// src/lib/env.ts — validate env vars at import time
import { z } from 'zod';

const envSchema = z.object({
  DATABASE_URL: z.string().url(),
  API_SECRET: z.string().min(16),
  NEXT_PUBLIC_API_URL: z.string().url(),
  VERCEL_ENV: z.enum(['production', 'preview', 'development']).default('development'),
  VERCEL_URL: z.string().optional(),
});

// Fails fast at startup if env vars are missing
export const env = envSchema.parse(process.env);

// Type-safe access throughout the app
// Usage: import { env } from '@/lib/env'; env.DATABASE_URL
```

### Step 3: Database Client (Lazy Singleton)

```typescript
// src/lib/db.ts — lazy init to minimize cold starts
import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined };

export const db = globalForPrisma.prisma ?? new PrismaClient({
  log: process.env.VERCEL_ENV === 'development' ? ['query'] : ['error'],
});

// Prevent multiple instances in development (hot reload)
if (process.env.VERCEL_ENV !== 'production') {
  globalForPrisma.prisma = db;
}
```

### Step 4: API Route Pattern

```typescript
// src/app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { env } from '@/lib/env';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const limit = Number(searchParams.get('limit') ?? 20);

    const users = await db.user.findMany({ take: limit });
    return NextResponse.json({ users }, {
      headers: { 'Cache-Control': 's-maxage=60, stale-while-revalidate=300' },
    });
  } catch (error) {
    console.error('GET /api/users failed:', error);
    return NextResponse.json(
      { error: 'Internal server error', requestId: crypto.randomUUID() },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const user = await db.user.create({ data: body });
    return NextResponse.json({ user }, { status: 201 });
  } catch (error) {
    console.error('POST /api/users failed:', error);
    return NextResponse.json(
      { error: 'Failed to create user' },
      { status: 400 }
    );
  }
}
```

### Step 5: Edge Middleware for Auth

```typescript
// src/middleware.ts
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Skip auth for public routes
  if (pathname.startsWith('/api/health') || pathname.startsWith('/api/webhooks')) {
    return NextResponse.next();
  }

  // Check auth for dashboard routes
  if (pathname.startsWith('/dashboard') || pathname.startsWith('/api/')) {
    const token = request.cookies.get('session')?.value;
    if (!token) {
      if (pathname.startsWith('/api/')) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }
      return NextResponse.redirect(new URL('/login', request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```

### Step 6: Health Check Endpoint

```typescript
// src/app/api/health/route.ts
import { db } from '@/lib/db';

export const dynamic = 'force-dynamic'; // Never cache health checks

export async function GET() {
  const checks: Record<string, 'ok' | 'error'> = {};

  // Database connectivity
  try {
    await db.$queryRaw`SELECT 1`;
    checks.database = 'ok';
  } catch {
    checks.database = 'error';
  }

  const allHealthy = Object.values(checks).every(v => v === 'ok');

  return Response.json({
    status: allHealthy ? 'healthy' : 'degraded',
    checks,
    version: process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7) ?? 'local',
    region: process.env.VERCEL_REGION ?? 'local',
    timestamp: new Date().toISOString(),
  }, {
    status: allHealthy ? 200 : 503,
  });
}
```

### Step 7: Vercel Configuration

```json
// vercel.json
{
  "regions": ["iad1"],
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "X-Content-Type-Options", "value": "nosniff" },
        { "key": "X-Frame-Options", "value": "DENY" },
        { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
      ]
    }
  ],
  "rewrites": [
    { "source": "/docs/:path*", "destination": "https://docs.example.com/:path*" }
  ],
  "redirects": [
    { "source": "/old-page", "destination": "/new-page", "permanent": true }
  ]
}
```

## Layer Responsibilities

| Layer | Runtime | Responsibilities |
|-------|---------|-----------------|
| Edge (middleware.ts) | V8 isolates | Auth, redirects, A/B testing, headers |
| Server (api routes) | Node.js | Database queries, business logic, webhooks |
| Static (pages) | CDN | Pre-rendered pages, ISR, images |
| Client (components) | Browser | Interactivity, client state |

## Output

- Layered project structure with clear separation of concerns
- Typed environment variables validated at startup
- Lazy-initialized database client minimizing cold starts
- Edge Middleware handling authentication before server layer
- Health check endpoint for deployment verification

## Error Handling

| Error | Cause | Solution |
|-------|-------|----------|
| Env validation fails on deploy | Missing required variable | Add to Vercel dashboard for target environment |
| Middleware runs on static assets | Matcher too broad | Add exclusions for `_next/static`, `_next/image` |
| Database connection pool exhausted | Too many concurrent functions | Use connection pooler (PgBouncer, Prisma Accelerate) |
| API route not found | Wrong directory structure | Must be in `src/app/api/` with `route.ts` filename |

## Examples

### Validate the layer boundary before production traffic

Implement edge middleware only for routing and authorization decisions, keep database access inside server routes, and expose a non-sensitive health endpoint that verifies dependency reachability without returning credentials. Deploy the architecture to preview, test static, edge, and server paths with synthetic identities, and measure middleware overhead. Preserve the prior deployment as rollback until observability confirms the new path is stable under normal traffic.

## Resources

- [Next.js Project Structure](https://nextjs.org/docs/getting-started/project-structure)
- [Vercel Project Configuration](https://vercel.com/docs/project-configuration)
- [Middleware Documentation](https://vercel.com/docs/functions/edge-middleware)
- [API Routes (App Router)](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)

## Next Steps

For multi-environment setup, see `vercel-multi-env-setup`.

© Jeremy Longshore · MIT · jeremylongshore/tons-of-skills-marketplace

Similar skills

All skills for Cloud: AWS, Azure, GCP →

From the same set139

The whole set →
customerio-cost-tuning customerio-cost-tuning audits a Customer.io workspace for wasted spend: which profiles inflate the bill, which accounts can go, where duplicate events pile up. CX Codex +1 1installs apollo-core-workflow-a apollo-core-workflow-a builds an Apollo.io lead generation pipeline in Claude Code to search prospects and enrich qualified contacts with verified emails and phone numbers. CX Codex +1 1installs firecrawl-migration-deep-dive The firecrawl-migration-deep-dive skill guides a move from Puppeteer, Playwright, Cheerio, or another scraper to Firecrawl v2, with checks for parity, policy, spend, and rollback. CX Codex +1 1installs vercel-webhooks-events vercel-webhooks-events — a skill for Claude Code, Codex, Cursor and other platforms that processes Vercel deployment events with HMAC signature verification. CX Codex +1 1installs vercel-policy-guardrails The vercel-policy-guardrails skill adds Vercel project checks for secret exposure, CI policy violations, Edge Runtime imports, and protected routes. CX Codex +1 1installs gcs-lifecycle-policy gcs-lifecycle-policy — a skill that handles lifecycle policy work in Google Cloud Storage. It activates on its own when a request mentions gcs or lifecycle policy. CX Codex +1 1installs gcs-bucket-config gcs-bucket-config automates Google Cloud Storage bucket configuration in Claude Code. Generates configs and gcloud commands for your storage setups. CX Codex +1 1installs s3-bucket-policy-generator The s3-bucket-policy-generator skill guides S3 bucket policy work, generates configurations, and checks results against common standards when AWS tasks call for it. CX Codex +1 1installs

Project sponsors

Companies that keep this analytics open