mcpField
V
vercel-deployment

vercel-deployment

github.com/curiositech云与 DevOps257178 次安装今天更新
代码仓库

关于 vercel-deployment

用于在 Vercel 上配置和部署 Next.js 应用的技能,适合负责应用上线的开发者。内容涵盖环境变量、构建、数据库、预览部署、域名、安全与故障排查。

主要功能

  1. 01环境变量配置
  2. 02构建与运行时配置
  3. 03数据库部署指导
  4. 04预览部署设置
  5. 05域名与安全指导
  6. 06故障排查与监控

适用场景

  1. 01准备在 Vercel 部署 Next.js 应用
  2. 02区分预览与生产环境设置
  3. 03诊断部署构建失败

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/curiositech/some_claude_skills --skill vercel-deployment

安装后在 Claude Code 中输入/vercel-deployment确认已加载。

附带文件.claude-plugin/plugin.json

详细介绍

Vercel 部署

此技能可帮助你按照最佳实践在 Vercel 上部署和配置 Next.js 应用。

快速部署检查清单

  • 在 Vercel 控制台中设置环境变量
  • 配置构建命令(默认:next build)
  • 输出目录正确(默认:.next)
  • 指定 Node.js 版本(建议使用 20.x)
  • Vercel 网络可以访问数据库
  • 未将密钥提交到 git

环境变量

设置变量

Vercel 控制台(建议用于设置密钥):

  1. 项目设置 → 环境变量
  2. 添加变量并设置适当的作用范围:
    • Production:仅用于生产部署
    • Preview:用于 PR 和分支预览
    • Development:用于本地 vercel dev

通过 CLI:

vercel env add VARIABLE_NAME production
vercel env pull .env.local  # Pull to local
变量命名
# Server-only (never exposed to browser)
DATABASE_URL=
SESSION_SECRET=
ANTHROPIC_API_KEY=

# Client-exposed (prefixed with NEXT_PUBLIC_)
NEXT_PUBLIC_APP_URL=
NEXT_PUBLIC_ANALYTICS_ID=
大小限制
上下文限制
每次部署的总量64 KB
Edge Functions每个变量 5 KB
单个变量最多 64 KB
此项目所需的变量
# Authentication (required)
SESSION_SECRET=your-32-char-minimum-secret-here

# AI Integration (required for chat)
ANTHROPIC_API_KEY=sk-ant-api...

# Database (if using external)
DATABASE_URL=file:./data/app.db

# Push Notifications (optional)
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
VAPID_SUBJECT=mailto:[email protected]

# OAuth (optional)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
APPLE_CLIENT_ID=
APPLE_CLIENT_SECRET=

vercel.json 配置

{
  "buildCommand": "npm run build",
  "framework": "nextjs",
  "regions": ["iad1"],
  "headers": [
    {
      "source": "/api/(.*)",
      "headers": [
        { "key": "Cache-Control", "value": "no-store, must-revalidate" }
      ]
    },
    {
      "source": "/(.*)",
      "headers": [
        { "key": "X-Content-Type-Options", "value": "nosniff" },
        { "key": "X-Frame-Options", "value": "DENY" },
        { "key": "X-XSS-Protection", "value": "1; mode=block" }
      ]
    }
  ],
  "redirects": [
    {
      "source": "/old-path",
      "destination": "/new-path",
      "permanent": true
    }
  ],
  "rewrites": [
    {
      "source": "/api/v1/:path*",
      "destination": "/api/:path*"
    }
  ]
}

TypeScript 配置(2025 年新增)

// vercel.ts - Type-safe configuration
import { defineConfig } from '@vercel/config';

export default defineConfig({
  regions: ['iad1'],

  headers: async () => [
    {
      source: '/api/:path*',
      headers: [
        { key: 'Cache-Control', value: 'no-store' },
      ],
    },
  ],

  redirects: async () => [
    {
      source: '/old',
      destination: '/new',
      permanent: true,
    },
  ],
});

Edge Functions

何时使用 Edge

适用于:

  • 身份验证/授权
  • A/B 测试
  • 基于地理位置的内容
  • 请求/响应转换
  • 简单、快速的操作

不适用于:

  • 数据库连接(请改用无服务器方案)
  • 长时间运行的操作
  • 大型依赖项
Edge Function 示例
// src/middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export const config = {
  matcher: ['/api/:path*', '/protected/:path*'],
};

export function middleware(request: NextRequest) {
  // Check auth token
  const token = request.cookies.get('session')?.value;

  if (!token && request.nextUrl.pathname.startsWith('/protected')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // Add headers
  const response = NextResponse.next();
  response.headers.set('X-Request-Id', crypto.randomUUID());

  return response;
}
API 路由中的 Edge Runtime
// src/app/api/edge-example/route.ts
export const runtime = 'edge';

export async function GET(request: Request) {
  // Limited to edge-compatible APIs
  return Response.json({ timestamp: Date.now() });
}

构建配置

package.json 脚本
{
  "scripts": {
    "build": "next build",
    "postbuild": "npm run db:generate"
  }
}
构建环境
# Set Node.js version
# In Vercel Dashboard → Settings → General → Node.js Version
# Or in package.json:
{
  "engines": {
    "node": "20.x"
  }
}
构建输出
# Check build locally
npm run build

# Analyze bundle
ANALYZE=true npm run build

数据库注意事项

Vercel 上的 SQLite

使用 better-sqlite3 的 SQLite 可在 Vercel 的无服务器函数中运行,但:

  • 除 /tmp 外,文件系统为只读
  • 数据不会在不同调用之间持久保存
  • 不适合存储生产数据
生产数据库选项
  1. Turso(SQLite 边缘数据库)

    import { createClient } from '@libsql/client';
    
    const db = createClient({
      url: process.env.TURSO_DATABASE_URL!,
      authToken: process.env.TURSO_AUTH_TOKEN,
    });
    
  2. Vercel Postgres

    import { sql } from '@vercel/postgres';
    
    const result = await sql`SELECT * FROM users`;
    
  3. PlanetScale(MySQL)

  4. Neon(Postgres)

预览部署

分支预览

每次 git push 都会创建预览部署:

  • https://<project>-<branch>-<team>.vercel.app
  • 预览环境使用单独的环境变量
预览环境变量
# Different values for preview vs production
# In Vercel Dashboard, set both:

DATABASE_URL (Production): postgres://prod-db...
DATABASE_URL (Preview): postgres://staging-db...
在 PR 中添加评论

Vercel 会自动在 PR 中添加评论,其中包括:

  • 预览 URL
  • 构建状态
  • 性能指标

故障排除

构建失败
# Check build locally first
npm run build

# Common issues:
# - Missing environment variables
# - TypeScript errors
# - ESLint errors (strict mode)
# - Missing dependencies
环境变量问题
# Verify variables are set
vercel env ls

# Pull to local for debugging
vercel env pull .env.local
函数超时
// Increase timeout (max 60s on Pro, 10s on Hobby)
// In vercel.json:
{
  "functions": {
    "api/long-running.ts": {
      "maxDuration": 60
    }
  }
}
内存问题
// Increase memory (affects cost)
{
  "functions": {
    "api/heavy-processing.ts": {
      "memory": 1024
    }
  }
}

监控

Vercel Analytics
// src/app/layout.tsx
import { Analytics } from '@vercel/analytics/react';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  );
}
Speed Insights
import { SpeedInsights } from '@vercel/speed-insights/next';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <SpeedInsights />
      </body>
    </html>
  );
}
函数日志
# View logs via CLI
vercel logs <deployment-url>

# Real-time logs
vercel logs <deployment-url> --follow

域名

设置自定义域名
  1. Vercel 控制台 → 域名
  2. 添加域名
  3. 配置 DNS:
    • A 记录:76.76.21.21
    • 或 CNAME:cname.vercel-dns.com
  4. 自动配置 SSL
重定向
// vercel.json
{
  "redirects": [
    {
      "source": "/:path((?!api/).*)",
      "has": [{ "type": "host", "value": "old-domain.com" }],
      "destination": "https://new-domain.com/:path",
      "permanent": true
    }
  ]
}

安全

受保护的路由

使用中间件执行身份验证检查(参见上文的 Edge Functions)。

速率限制

由于 Vercel 不为无服务器函数提供内置速率限制,因此请在应用层实现速率限制。

密钥管理
  • 切勿提交 .env 文件
  • 使用 Vercel 的加密环境变量
  • 定期轮换密钥
  • 为预览环境和生产环境使用不同的密钥

参考资料

评论

支持 Markdown