vercel-reference-architecture

0
0
Source

Implement Vercel reference architecture with best-practice project layout. Use when designing new Vercel integrations, reviewing project structure, or establishing architecture standards for Vercel applications. Trigger with phrases like "vercel architecture", "vercel best practices", "vercel project structure", "how to organize vercel", "vercel layout".

Install

mkdir -p .claude/skills/vercel-reference-architecture && curl -L -o skill.zip "https://mcp.directory/api/skills/download/7443" && unzip -o skill.zip -d .claude/skills/vercel-reference-architecture && rm skill.zip

Installs to .claude/skills/vercel-reference-architecture

About this skill

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

// 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)

// 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

// 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

// 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

// 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

// 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

LayerRuntimeResponsibilities
Edge (middleware.ts)V8 isolatesAuth, redirects, A/B testing, headers
Server (api routes)Node.jsDatabase queries, business logic, webhooks
Static (pages)CDNPre-rendered pages, ISR, images
Client (components)BrowserInteractivity, 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

ErrorCauseSolution
Env validation fails on deployMissing required variableAdd to Vercel dashboard for target environment
Middleware runs on static assetsMatcher too broadAdd exclusions for _next/static, _next/image
Database connection pool exhaustedToo many concurrent functionsUse connection pooler (PgBouncer, Prisma Accelerate)
API route not foundWrong directory structureMust be in src/app/api/ with route.ts filename

Resources

Next Steps

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

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

3114

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

1128

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571699

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.