Современный деплой
Vercel и Netlify революционизировали деплой веб-приложений. Push в Git — и через минуту сайт в production. Рассмотрим возможности обеих платформ.
Vercel — для Next.js и не только
Vercel — создатели Next.js, поэтому интеграция идеальна:
# Установка CLI
npm i -g vercel
# Деплой из командной строки
vercel
# Деплой в production
vercel --prod
# Связь с Git репозиторием
vercel link
Конфигурация vercel.json
// vercel.json
{
"buildCommand": "npm run build",
"outputDirectory": ".next",
"framework": "nextjs",
"regions": ["fra1"],
"env": {
"DATABASE_URL": "@database-url"
},
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Cache-Control", "value": "no-store" }
]
}
],
"redirects": [
{
"source": "/old-page",
"destination": "/new-page",
"permanent": true
}
],
"rewrites": [
{
"source": "/blog/:slug",
"destination": "/posts/:slug"
}
]
}
Netlify — универсальный хостинг
# netlify.toml
[build]
command = "npm run build"
publish = ".next"
[build.environment]
NODE_VERSION = "20"
[[redirects]]
from = "/old/*"
to = "/new/:splat"
status = 301
[[headers]]
for = "/*"
[headers.values]
X-Frame-Options = "DENY"
X-Content-Type-Options = "nosniff"
# Функции
[functions]
directory = "netlify/functions"
# Edge Functions
[[edge_functions]]
path = "/api/*"
function = "api-handler"
Preview Deployments
Каждый Pull Request получает уникальный URL для preview:
# Автоматически при PR:
# - Vercel: https://project-git-branch-team.vercel.app
# - Netlify: https://deploy-preview-123--project.netlify.app
# Комментарий в PR с ссылкой на preview
# Можно тестировать изменения до merge
Serverless Functions
// Vercel: api/hello.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
return NextResponse.json({ message: 'Hello from Vercel!' });
}
// Netlify: netlify/functions/hello.ts
import { Handler } from '@netlify/functions';
export const handler: Handler = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Netlify!' })
};
};
Edge Functions
Edge Functions выполняются ближе к пользователю:
// Vercel Edge: middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Геолокация
const country = request.geo?.country || 'US';
// A/B тестирование
const bucket = Math.random() < 0.5 ? 'a' : 'b';
const response = NextResponse.next();
response.cookies.set('ab-bucket', bucket);
return response;
}
export const config = {
matcher: '/((?!api|_next/static|favicon.ico).*)'
};
// Netlify Edge: netlify/edge-functions/geo.ts
import { Context } from '@netlify/edge-functions';
export default async (request: Request, context: Context) => {
const country = context.geo.country?.code || 'US';
return new Response(JSON.stringify({ country }), {
headers: { 'content-type': 'application/json' }
});
};
Environment Variables
# Vercel CLI
vercel env add DATABASE_URL production
vercel env pull .env.local
# Netlify CLI
netlify env:set DATABASE_URL "postgres://..."
netlify env:import .env
# В dashboard обеих платформ:
# Settings → Environment Variables
# Можно задать разные значения для:
# - Production
# - Preview
# - Development
Настройка домена
# Vercel
vercel domains add example.com
# DNS: A record → xxx.xxx.xxx.xxx
# или CNAME → cname.vercel-dns.com
# Netlify
netlify domains:add example.com
# DNS: A record → xxx.xxx.xxx.xxx
# или CNAME → [site-name].netlify.app
# SSL сертификаты — автоматически через Let's Encrypt
Сравнение платформ
| Критерий | Vercel | Netlify |
|---|---|---|
| Next.js | ✅ Идеально | Хорошо |
| Статика | Отлично | ✅ Отлично |
| Functions | Serverless | Serverless + Background |
| Edge | ✅ Middleware | Edge Functions |
| Forms | Нет | ✅ Встроенные |
| CMS | Нет | ✅ Netlify CMS |
| Цена | Похожая | Похожая |
Заключение
Vercel идеален для Next.js проектов с edge-функциями. Netlify универсальнее и предлагает больше встроенных функций. Обе платформы обеспечивают отличный DX и быстрый деплой.
Выбирайте платформу под стек. Next.js → Vercel. Статика или другие фреймворки → Netlify или Vercel.
