跳转至

Vercel 前端部署平台

一句话概述:Vercel 是前端和全栈应用的最佳部署平台,git push 自动部署,全球 CDN 加速,内置 Serverless 函数,对 Next.js 支持最好(Vercel 就是 Next.js 的公司)。

核心知识点

概念白话解释
自动部署连接 GitHub 后,push 代码自动构建部署
Preview 部署每个 PR 自动生成预览链接,方便团队审查
Serverless Functions后端 API 函数,自动扩缩容
Edge Functions在全球边缘节点运行的函数,延迟更低
Edge Config全球分布的配置存储,用于功能开关、A/B 测试
126 个节点Vercel 全球有 126 个边缘节点,静态资源加速

安装配置

# 安装 Vercel CLI
npm install -g vercel  # 全局安装

# 登录
vercel login  # 打开浏览器授权

# 部署(在项目目录执行)
vercel  # 首次部署,交互式配置
vercel --prod  # 部署到生产环境

连接 GitHub 自动部署

1. 访问 https://vercel.com
2. 点击 "New Project"
3. 导入 GitHub 仓库
4. 配置构建设置(通常自动检测)
5. 点击 "Deploy"

之后每次 push 到 main 自动部署到生产
每个 PR 自动创建预览环境

项目配置

// vercel.json - 项目配置(可选)
{
  "framework": "nextjs",  // 框架类型(自动检测)
  "buildCommand": "npm run build",  // 构建命令
  "outputDirectory": ".next",  // 构建输出目录
  "installCommand": "npm install",  // 安装命令
  "regions": ["sin1"],  // Serverless 函数区域(新加坡)
  "headers": [
    {
      "source": "/api/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Origin", "value": "*" }
      ]
    }
  ],
  "redirects": [
    { "source": "/old-page", "destination": "/new-page", "permanent": true }
  ],
  "rewrites": [
    { "source": "/api/:path*", "destination": "https://backend.example.com/:path*" }
  ]
}

基本使用

Next.js 部署(零配置)

# 创建 Next.js 项目
npx create-next-app@latest my-app  # 创建项目
cd my-app

# 本地开发
npm run dev  # http://localhost:3000

# 部署到 Vercel
vercel  # 自动检测 Next.js,零配置部署

# 或者推送到 GitHub 自动部署
git add . && git commit -m "初始提交"
git push origin main  # Vercel 自动检测并部署

Serverless API 函数

// api/hello.ts(Next.js App Router)
// 或 app/api/hello/route.ts
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const name = searchParams.get('name') || '世界'  // 获取查询参数

  return NextResponse.json({  // 返回 JSON
    message: `你好, ${name}!`,
    timestamp: new Date().toISOString(),
  })
}

export async function POST(request: Request) {
  const body = await request.json()  // 解析请求体
  return NextResponse.json({ received: body }, { status: 201 })
}

环境变量

# CLI 设置环境变量
vercel env add DATABASE_URL  # 交互式添加
vercel env pull .env.local  # 拉取远程环境变量到本地

# Vercel 面板设置
# Settings → Environment Variables
# 可以区分 Production / Preview / Development

高级用法

Edge Functions

// app/api/fast/route.ts - Edge Runtime(更快)
export const runtime = 'edge'  // 使用 Edge Runtime

export async function GET(request: Request) {
  return new Response(JSON.stringify({
    message: '来自边缘节点的响应',
    region: request.headers.get('x-vercel-id'),  // 显示服务节点
  }), {
    headers: { 'Content-Type': 'application/json' },
  })
}

自定义域名

# CLI 添加域名
vercel domains add example.com  # 添加自定义域名

# 或在面板操作
# Settings → Domains → Add Domain
# 然后在你的域名服务商添加 DNS 记录

部署保护

// vercel.json
{
  "passwordProtection": {
    "deploymentType": "preview"  // 预览部署需要密码
  }
}

Vercel Cron Jobs

// vercel.json - 定时任务
{
  "crons": [
    {
      "path": "/api/cron/cleanup",  // 定时调用的 API 路径
      "schedule": "0 * * * *"  // 每小时
    }
  ]
}

常见报错

报错信息原因解决方案
Build failed构建命令出错检查构建日志和 buildCommand
Function timeoutServerless 函数超时Hobby 10秒/Pro 300秒,优化代码
FUNCTION_INVOCATION_FAILED函数运行时出错检查 vercel logs 看详细错误
404 Not Found路由配置问题检查 rewrites 和文件路径
环境变量拿不到没设置或没重新部署在面板设置后重新部署
域名 SSL 报错DNS 没配置好检查 CNAME/A 记录指向 Vercel

速查表

# CLI 命令
vercel                    # 部署到 Preview
vercel --prod             # 部署到 Production
vercel dev                # 本地开发(模拟 Vercel 环境)
vercel env add <名称>     # 添加环境变量
vercel env pull           # 拉取环境变量到本地
vercel logs               # 查看日志
vercel domains add <域名> # 添加自定义域名
vercel inspect <url>      # 查看部署详情
vercel rollback           # 回滚到上一个部署

# 支持的框架(零配置)
Next.js / Nuxt / Remix / SvelteKit / Astro
React (CRA/Vite) / Vue / Angular / Gatsby
Hugo / Jekyll / Hexo

# 免费额度(Hobby Plan)
# 无限静态站点
# Serverless 函数:100GB-hours/月
# 带宽:100GB/月
# 构建:每次 45 分钟超时
# 函数超时:10 秒
# 自定义域名数量:无限

参考:Vercel 官网 | Vercel 文档 | Next.js 部署指南