⏱️ Estimated read: 10 min
|
🖨️ Print / PDF
|
🔗 Copy Link
Dense reference for the Vercel surface covered across the series: CLI, vercel.json, functions, caching, Firewall, Deployment Protection, BotID, monorepos, Turborepo, prebuilt deploys, Deploy Hooks, and observability. Numbers marked ≈ move with plan changes — verify against current pricing before committing to a budget.
Quick How-To Guides & Fast Fixes Need a quick fix or step-by-step solution? Browse our fast answers on HowTo.KandZ.me :
CLI Commands
Command Purpose vercelDeploy to preview vercel --prodDeploy to production vercel devLocal dev with functions + env vercel linkLink directory to a project vercel pullFetch project settings + env into .vercel vercel buildBuild locally → .vercel/output vercel deploy --prebuiltUpload prebuilt output vercel lsList deployments vercel inspect <url>Deployment details, build logs vercel logs <url>Runtime log stream vercel promote <url>Move a deployment to production vercel rollback <url>Revert production to a prior deployment vercel env ls / add / rm / pullManage env vars vercel alias set <url> <domain>Point a domain at a deployment vercel domains ls / addManage domains vercel git connectConnect a git repo vercel whoami / vercel switchAccount / team
# Standard CI sequence
vercel pull --yes --environment=production --token="$VERCEL_TOKEN"
vercel build --prod --token="$VERCEL_TOKEN"
vercel deploy --prebuilt --prod --token="$VERCEL_TOKEN"
vercel.json Top-Level Keys
Key Type Effect buildCommandstring Override detected build installCommandstring Override install outputDirectorystring Where static output lives frameworkstring Skip framework auto-detection regionsstring[] Function regions functionsobject Per-route memory, duration, region cronsarray Scheduled invocations rewritesarray Internal path mapping redirectsarray 3xx responses headersarray Response header rules cleanUrlsboolean Drop .html from URLs trailingSlashboolean Enforce trailing slash imagesobject Image optimizer domains + sizes logDrainsarray Stream logs to external endpoint publicboolean Disable Deployment Protection (deprecated in favor of dashboard) github / gitlab / bitbucketobject Git integration toggles
{
"buildCommand": "turbo run build --filter=web...",
"installCommand": "pnpm install --frozen-lockfile",
"outputDirectory": "apps/web/.next",
"regions": ["iad1"],
"cleanUrls": true,
"trailingSlash": false
}
Routing Rules
{
"rewrites": [
{ "source": "/api/:path*", "destination": "/api/:path*" },
{ "source": "/blog/:slug", "destination": "/posts/:slug" },
{ "source": "/legacy", "destination": "/docs", "permanent": false }
],
"redirects": [
{ "source": "/old", "destination": "/new", "permanent": true },
{ "source": "/u/:handle", "destination": "/@:handle", "permanent": false }
],
"headers": [
{
"source": "/api/(.*)",
"headers": [{ "key": "Cache-Control", "value": "no-store" }]
}
]
}
Field Meaning sourceIncoming path pattern destinationTarget path or URL permanenttrue → 308, false → 307hasMatch on header/cookie/query missingMatch when the field is absent :param / :param*Single segment / catch-all
Evaluation order: headers → redirects → rewrites → filesystem → 404.
Functions Configuration
{
"functions": {
"app/api/report/route.ts": {
"memory": 3009,
"maxDuration": 60,
"regions": ["iad1"]
},
"app/api/webhook/route.ts": {
"memory": 1024,
"maxDuration": 10,
"regions": ["iad1", "fra1"]
}
}
}
Setting Values Notes memory128 / 256 / 512 / 1024 / 2048 / 3009 MB Default 1024 maxDurationHobby ≈10s default, 60s max Pro ≈15s default, 300s max regionsRegion codes Default = closest to caller runtimenodejs20.x, nodejs22.x, edgeSet via export, not JSON
// Per-route overrides in the app router
export const runtime = "nodejs";
export const maxDuration = 60;
export const dynamic = "force-dynamic";
export const revalidate = 0;
Caching and Rendering
Export Effect Cost revalidate = falseFully static, built once Zero invocations revalidate = 3600ISR, hourly regeneration 24 invocations/day revalidate = 0Dynamic, every request One invocation per request dynamic = "force-static"Force static rendering Zero invocations dynamic = "force-dynamic"Force per-request One invocation per request fetch(url, { next: { revalidate: 60 } })Per-fetch data cache Cached upstream fetch(url, { cache: "no-store" })Bypass data cache Every request
// On-demand revalidation from a webhook
import { revalidatePath, revalidateTag } from "next/cache";
revalidatePath("/pricing"); // invalidate one route
revalidateTag("products"); // invalidate every tagged fetch
// Response-level cache headers for a static asset
{ "headers": [{ "source": "/img/(.*)", "headers": [
{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
]}]}
Environment Variables
Scope Where Set Production / Preview / Development Project settings, per key Pull Request overrides Deploy settings System (auto) VERCEL_URL, VERCEL_ENV, VERCEL_GIT_*Automation VERCEL_AUTOMATION_BYPASS_SECRET
# Pull all env for an environment into .env.local
vercel env pull .env.local --environment=development
# Add for three targets at once
printf 'value' | vercel env add API_URL production preview
Variable Value VERCEL_ENVproduction / preview / developmentVERCEL_URLDeployment URL (no protocol) VERCEL_BRANCH_URLStable branch alias VERCEL_PROJECT_PRODUCTION_URLProduction domain VERCEL_GIT_COMMIT_SHACommit hash VERCEL_GIT_COMMIT_REFBranch name VERCEL_GIT_PULL_REQUEST_IDPR number
Only NEXT_PUBLIC_* / VITE_* / PUBLIC_* prefixes reach the browser. A server secret with a public prefix is a leaked secret.
Build Output API v3
.vercel/
└── output/
├── config.json ← routes, functions, overrides
├── static/ ← served as-is
│ └── index.html
└── functions/
└── api/
└── hello.func/
├── .vc-config.json
└── index.js
// .vercel/output/config.json
{
"version": 3,
"routes": [
{ "src": "/api/(.*)", "dest": "/api/$1" },
{ "handle": "filesystem" },
{ "src": "/.*", "dest": "/index.html", "status": 404 }
]
}
// .vercel/output/functions/api/hello.func/.vc-config.json
{
"runtime": "nodejs22.x",
"handler": "index.js",
"memory": 1024,
"maxDuration": 10
}
Firewall — Conditions, Operators, Actions
{
"name": "Challenge foreign logins",
"active": true,
"action": { "mitigate": { "action": "challenge" } },
"conditionGroup": [
{
"conditions": [
{ "type": "path", "op": "eq", "value": "/api/login" },
{ "type": "method", "op": "eq", "value": "POST" },
{ "type": "country", "op": "neq", "value": "US" }
]
}
]
}
Field type Matches pathPath without query methodHTTP method hostHostname ip_addressClient IP user_agentUser agent countryGeoIP code headerNamed header (key + value) ja3_digest / ja4_digestTLS fingerprint
Operator Meaning eq / neqEqual / not equal subContains substring pre / sufPrefix / suffix reRegex incIn list
Action Effect logRecord only challengeJS challenge, browsers pass deny403 at the edge bypassShort-circuit remaining rules rate_limitCount then mitigate
Grouping: conditions inside one group = AND. Separate groups = OR.
// Rate limit keyed on IP + header
{ "mitigate": { "action": "rate_limit",
"rateLimit": { "requests": 20, "window": "60s", "keys": ["ip", "header"] } } }
Key Scope ipPer client address headerPer header value (needs key) path / hostCoarse global limit
Managed rulesets: OWASP CRS and Vercel Managed Ruleset. Both take an action and a paranoia level (1–4). Start level 1 with log.
IP blocking: individual addresses and CIDR ranges, evaluated before custom rules, effective immediately, scoped per project.
Deployment Protection
Mode Plan Identity Vercel Authentication All Vercel account Password Protection Pro+ Shared password Trusted IPs Enterprise CIDR allowlist Bypass secret All x-vercel-protection-bypass
Scope Preview Prod domain *.vercel.app prodStandard Protected Public Protected All Deployments Protected Protected Protected
// Server-side call through protection
await fetch(`${previewUrl}/api/health`, {
headers: { "x-vercel-protection-bypass": process.env.VERCEL_AUTOMATION_BYPASS_SECRET! },
});
// Browser automation: header + cookie establishment
use: { extraHTTPHeaders: { "x-vercel-protection-bypass": secret } }
The cookie variant adds x-vercel-set-bypass-cookie: true, which sets _vercel_jwt for subsequent navigations. Never pass the secret as a query param.
BotID
// next.config.ts
import { withBotId } from "botid/next/config";
export default withBotId({ reactStrictMode: true });
// instrumentation-client.ts
import { initBotId } from "botid/client/core";
initBotId({
protect: [
{ path: "/api/signup", method: "POST" },
{ path: "/api/login", method: "POST" },
],
});
// app/api/signup/route.ts
import { checkBotId } from "botid/server";
import { NextResponse } from "next/server";
export async function POST() {
const { isBot, isVerifiedBot } = await checkBotId();
if (isBot && !isVerifiedBot) {
return NextResponse.json({ error: "denied" }, { status: 403 });
}
return NextResponse.json({ ok: true });
}
Verdict Meaning isBot: falseHuman verdict isBot: true, isVerifiedBot: trueVerified crawler isBot: true, isVerifiedBot: falseGeneric automation
All three pieces are required: config wrap, client registration, server check. Missing the client half makes every request look human.
Monorepo and Turborepo
turbo run build --filter=web # the app only
turbo run build --filter=web... # app + its dependencies
turbo run build --filter=...^web # dependencies only
turbo run build --filter=./apps/* # by directory
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["tsconfig.base.json"],
"remoteCache": { "signature": true },
"tasks": {
"build": {
"dependsOn": ["^build"],
"inputs": ["$TURBO_DEFAULT$", ".env.production"],
"env": ["NEXT_PUBLIC_API_URL"],
"outputs": [".next/**", "!.next/cache/**", "dist/**"]
},
"lint": { "cache": false }
}
}
Setting Effect outputsFiles restored on a cache hit inputsFiles included in the hash envVars included in the hash cache: falseTask never cached dependsOn: ["^build"]Build upstream packages first
# Remote cache credentials
export TURBO_TOKEN="<vercel-access-token>"
export TURBO_TEAM="<team-slug>"
# Ignored Build Step — exit 0 skips, exit 1 builds
npx turbo-ignore web --fallback=HEAD^
Vercel project Root Directory Ignored Build Step acme-web apps/webnpx turbo-ignore web --fallback=HEAD^acme-docs apps/docsnpx turbo-ignore docs --fallback=HEAD^acme-dashboard apps/dashboardnpx turbo-ignore dashboard --fallback=HEAD^
Prebuilt Deploys
- run: npx vercel pull --yes --environment=production --token=$VERCEL_TOKEN
- run: npx vercel build --prod --token=$VERCEL_TOKEN
- run: npx vercel deploy --prebuilt --prod --token=$VERCEL_TOKEN
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
Variable Source VERCEL_TOKENAccount access token VERCEL_ORG_IDProject settings VERCEL_PROJECT_IDProject settings TURBO_TOKEN / TURBO_TEAMCache credentials
Rule: the --environment flag on pull and the --prod flag on build/deploy must agree. A mismatch is silent and produces a production deployment pointing at staging env.
Deploy Hooks
# Default branch
curl -X POST "https://api.vercel.com/v1/integrations/deploy/prj_xxx/hook_yyy"
# Named branch
curl -X POST "$HOOK_URL" -H "Content-Type: application/json" -d '{"ref":"content/spring"}'
Property Value Method POSTAuth The URL is the credential Branch Fixed at creation Response Deployment ID + URL Rotation Delete + recreate (new hook does not revoke old)
Observability
Surface Collects Retention Runtime Logs stdout / stderr per invocation 1h Hobby, 1d Pro, 3d Enterprise Observability Plus Logs + queries 30 days, ≈$10/project/mo Log Drain Streamed to your endpoint Unbounded (your store) Speed Insights Field Core Web Vitals Percentile per route Web Analytics Pageviews, referrers, events Cookie-free
Metric Good Poor above LCP ≤ 2.5s 4.0s INP ≤ 200ms 500ms CLS ≤ 0.1 0.25 FCP ≤ 1.8s 3.0s TTFB ≤ 800ms 1.8s
// Log drain
{
"logDrains": [{
"deliveryFormat": "ndjson",
"url": "https://logs.example.com/ingest",
"sources": ["lambda", "build", "edge", "static"],
"environments": ["production", "preview"]
}]
}
// Structured log — queryable, correlates by request ID
console.log(JSON.stringify({ event: "checkout.complete", orderId, durationMs }));
// Speed Insights mount
import { SpeedInsights } from "@vercel/speed-insights/next";
<SpeedInsights sampleRate={0.1} />
// Web Analytics mount + custom event
import { Analytics, track } from "@vercel/analytics/next";
<Analytics />
track("purchase_clicked", { sku, price: 49.99 });
Fluid Compute and Cost
// CPU-bound: more memory → less Active CPU → total cost can drop
"app/api/report/route.ts": { "memory": 3009, "maxDuration": 60 }
// I/O-bound: more memory → more Provisioned Memory → no gain
"app/api/webhook/route.ts": { "memory": 1024, "maxDuration": 10 }
Line item Rate (Pro, ≈) Basis Active CPU $0.128 / CPU-hour Execution milliseconds Provisioned Memory $0.0106 / GB-hour Memory × full duration Invocations $0.60 / million Request count Fast Data Transfer $0.15 / GB Egress
Lever Effect Cost ISR / edge cache Removes the invocation $0 Region pinning Latency, not cost $0 Memory tuning Halves Active CPU Free Sampling Downsizes telemetry Saves metric fee
Mental model: a request that awaits a query for 1,900ms and parses for 100ms bills 100ms of Active CPU and 2,000ms of Provisioned Memory plus one invocation. Wall-clock and CPU are different quantities.
Crons
{
"crons": [
{ "path": "/api/refresh-prices", "schedule": "0 * * * *" },
{ "path": "/api/nightly-report", "schedule": "0 3 * * *" }
]
}
Plan Crons Minimum interval Hobby ≈2 Once per day Pro ≈40 Once per minute Enterprise ≈100 Once per minute
Cron requests include Authorization: Bearer $CRON_SECRET when the secret is set — verify it in the handler or the route is public.
export async function GET(request: Request) {
if (request.headers.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`) {
return new Response("Unauthorized", { status: 401 });
}
// ... job body
}
Limits and Quotas
Limit Value Function response body 4.5 MB Node function bundle (unzipped) 250 MB Edge function bundle ≈4 MB Node function default duration 15s (Pro), 300s max Edge function wall clock ≈30s Static file request timeout 30s Deployments / day (Hobby) ≈100 Concurrent builds (Pro) ≈12 Build duration 45 min Env var value size 64 KB Project domains ≈50 per project
Error Status Codes
Code Meaning Common Cause 401 Unauthorized Protection gate, missing bypass 403 Forbidden Firewall deny, BotID block 404 Not found Rewrite destination wrong, root directory wrong 405 Method not allowed GET exported where POST was called413 Payload too large Request beyond 4.5 MB 429 Rate limited Firewall rule, upstream API 500 Function error Uncaught throw; check runtime logs 502 Bad gateway Function crashed mid-stream 504 Gateway timeout Exceeded maxDuration FUNCTION_INVOCATION_FAILEDBuild artifact broken Rebuild; check .vc-config.json FUNCTION_PAYLOAD_TOO_LARGERequest body over limit Stream, or use object storage MIDDLEWARE_INVOCATION_TIMEOUTMiddleware exceeded limit Move work into the route
Gotchas
Symptom Cause Fix Env change not visible Cached at build time Redeploy NEXT_PUBLIC_* missingNot inlined at build Set before build, redeploy Preview is public Standard scope on *.vercel.app Enable protection Preview 401 in CI Bypass secret not set x-vercel-protection-bypassEvery push rebuilds all apps No Ignored Build Step turbo-ignoreCache serves old bundle Env var missing from hash Add to turbo.json env ISR never hits force-dynamic presentRemove the export Referrer shows direct Referer stripped cross-originUse UTM params Analytics event groups fragment Dynamic track name Constant name Bill spiked after tuning Memory raised on I/O-bound route Revert to 1024 Cron route publicly callable No CRON_SECRET check Verify the header Redirect loops Conflicting rewrite + redirect Order: headers → redirects → rewrites Regex route never matches Path includes query string Match path, not full URL Function times out on large payload 4.5 MB response cap Stream or paginate vercel build uses wrong envpull environment mismatchLock flags in one job Old deployment served Alias points at prior deploy vercel promoteBuild succeeds, 404 at runtime Wrong outputDirectory Point at the build output
One-Line Commands
vercel --prod --yes # deploy prod, no prompts
vercel rollback <deployment-url> # revert production
vercel logs <deployment-url> --follow # tail runtime logs
vercel env pull .env.local --environment=production # grab prod env locally
vercel inspect <deployment-url> --logs # read build logs
vercel domains add example.com # attach a domain
vercel alias set <deployment-url> example.com # point domain manually
vercel build && vercel deploy --prebuilt # prebuilt locally
npx turbo-ignore web --fallback=HEAD^ # skip-if-unchanged
curl -X POST "$HOOK_URL" -d '{}' # fire a deploy hook
← Previous Vercel 18 ▲ Observability & Cost Optimization — Inspecting runtime logs, Speed Insights, Web Analytics, and Fluid active CPU usage
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for: ✅ Finance (Mortgage, Interest, Inflation) ✅ Tech (Base64, JSON, Dev Suite, IP) ✅ Health (BMI, BMR, TDEE) ✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private 🔒 No data leaves your device 💎 100% Free
🔗 Use it now: https://tools.kandz.me 🔖 Bookmark it—you’ll need it later!