Vercel - Serverless Deployment Platform for Frontend Frameworks
Complete guide to Vercel - the leading serverless deployment platform for frontend frameworks. Covers installation, project setup, deployments, serverless functions, Edge Network, analytics, and advanced features.
- Step 1
Overview
Vercel is a cloud platform for static sites and serverless functions, built by the creators of Next.js. It provides a unified platform to build, deploy, and host web applications with zero configuration.
Key capabilities:
- Zero-config deployments: Automatic optimization for 35+ frameworks
- Preview deployments: Every PR creates a live preview URL
- Edge Network: Global CDN with 100+ edge locations
- Serverless Functions: Backend code that scales automatically
- Analytics: Built-in performance and user analytics
- CLI Tools: Local development with
vercel dev
Why Vercel:
- Optimized for Next.js: Built by the same team, deepest integration
- Developer Experience: Fastest path from code to production
- Scalability: Handles traffic spikes automatically
- Collaboration: Team features, comments, and deployment protection
- Enterprise Ready: SSO, audit logs, compliance certifications
Official site: https://vercel.com GitHub: https://github.com/vercel/vercel (15K+ stars) Documentation: https://vercel.com/docs CLI Reference: https://vercel.com/docs/cli - Step 2
Installation and Setup
Install the Vercel CLI globally to deploy projects and run local development servers.
Installation options:
- npm: Standard global installation
- yarn: For yarn users
- pnpm: For pnpm workspaces
- Docker: Container-based deployments
# Install Vercel CLI globally with npm npm i -g vercel # Verify installation vercel --version # Alternative installation methods yarn global add vercel pnpm add -g vercel # For local development with native binary (optional) npm i -g @vercel/vc-native --force # Login to Vercel vercel login # Choose authentication method: # 1. GitHub (recommended) # 2. GitLab # 3. Bitbucket # 4. Email # List connected accounts vercel ls # Logout if needed vercel logout - Step 3
Creating Your First Project
Set up a simple project to understand the deployment flow. Vercel supports 35+ frameworks out of the box.
Supported frameworks:
- Next.js (native support)
- React, Vue, Svelte
- Gatsby, Hugo, Jekyll
- Nuxt, Astro, Eleventy
- And many more...
# Create a simple Next.js project npx create-next-app@latest my-vercel-app # Follow prompts, accept defaults cd my-vercel-app # Start local development npm run dev # Visit http://localhost:3000 # Alternative: Vercel local dev server vercel dev # This proxies through Vercel's edge network locally # Deploy to Vercel for the first time vercel # Prompts: # 1. Set up and deploy? [Y/n] # 2. Which scope? (select your account) # 3. Link to existing project? [N/y] # 4. Project name? my-vercel-app # 5. In which directory is your code? ./ # 6. Want to override? [N/y] # Your app is now live! Example URL: # https://my-vercel-app-abc123.vercel.app - Step 4
Deployment Methods
Vercel offers multiple deployment methods for different workflows:
Deployment options:
- Git Integration: Automatic deployments on push
- CLI: Manual deployments from terminal
- Drag & Drop: Upload static files via web UI
- API: Programmatic deployments
# Method 1: Git Integration (recommended) # 1. Push code to GitHub/GitLab/Bitbucket # 2. Import project at vercel.com/new # 3. Every push creates a deployment # Method 2: CLI Deploy to Production vercel --prod # Deploy to Preview (default) vercel # Deploy with custom name vercel --name my-custom-deployment # Deploy specific environment vercel --env-use-redirects # Method 3: Link to existing project first cd my-project vercel link # Select existing project # Then deploy vercel --prod # Method 4: Deploy to specific team/account vercel --team your-team-slug # Method 5: API Deployment (scripted) # Create deployment with API token export VERCEL_TOKEN="your-token" # Get project ID curl -H "Authorization: Bearer $VERCEL_TOKEN" \ "https://api.vercel.com/v1/projects?teamId=YOUR_TEAM_ID" \ | jq '.projects[0].uuid' # Create deployment curl -X POST -H "Authorization: Bearer $VERCEL_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "project": "YOUR_PROJECT_ID", "files": [{"file": "index.html", "body": "<h1>Hello</h1>"}] }' \ "https://api.vercel.com/v1/deployments" - Step 5
Project Configuration
Configure your project using
vercel.jsonfor build settings, routes, and rewrites.Configuration sections:
- build: Build command and output directory
- installCommand: Custom install script
- routes: Rewrites, redirects, headers
- headers: Custom HTTP headers
- env: Environment variables (use UI for secrets)
{ "build": { "cmd": "npm run build", "output": ".next", "dev": "npm run dev" }, "installCommand": "npm install", "framework": "nextjs", "regions": ["iad1"], "headers": [ { "source": "/(.*). "headers": [ { "key": "X-Frame-Options", "value": "DENY" }, { "key": "X-Content-Type-Options", "value": "nosniff" }, { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" } ] }, { "source": "/api/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" } ] } ], "rewrites": [ { "source": "/app/(.*)", "destination": "/$1" }, { "source": "/old-path", "destination": "/new-path" } ], "redirects": [ { "source": "/deprecated", "destination": "/current", "permanent": true }, { "source": "/blog/:path*", "destination": "https://medium.com/@author/:path*", "statusCode": 302 } ], "cleanUrls": true, "trailingSlash": false, "spa": false } - Step 6
Environment Variables
Manage environment variables securely through the Vercel dashboard or CLI. Different variables can be set for Preview and Production environments.
Best practices:
- Use UI for sensitive variables
- Set different values per environment
- Variables are automatically injected at build and runtime
# Method 1: Set via Vercel Dashboard (recommended) # 1. Go to Project Settings -> Environment Variables # 2. Add variable with key, value, and environment scope # 3. Variables auto-inject on next deployment # Method 2: Link local env file # Create .env.local (gitignored) # DB_URL=postgresql://user:pass@host:5432/db # API_KEY=secret123 # Deploy with local env (links to project) vercel env pull .env.local # List environment variables vercel env ls # Add environment variable via CLI vercel env add DATABASE_URL # Enter value, select environments (Preview/Production) # Remove environment variable vercel env rm DATABASE_URL # Export env for local development vercel env pull .env.local # In your code, access via process.env // Node.js / Next.js API routes const dbUrl = process.env.DATABASE_URL; // Next.js runtime // Get Server Side Props export async function getServerSideProps() { const apiKey = process.env.API_KEY; return { props: { apiKey } }; } - Step 7
Serverless Functions
Vercel Serverless Functions let you write backend code without managing servers. Functions auto-scale and are optimized for serverless execution.
Function types:
- API Routes: Next.js
/api/*files - Functions Directory:
functions/*.jsin any framework - Lambda: Custom AWS Lambda deployment
// Next.js API Route: pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello from Vercel!', timestamp: new Date().toISOString(), headers: req.headers }); } // Next.js 13+ App Router: app/api/hello/route.js import { NextResponse } from 'next/server'; export async function GET(request: Request) { const searchParams = new URL(request.url).searchParams; const name = searchParams.get('name') || 'World'; return NextResponse.json({ message: `Hello, ${name}!`, timestamp: new Date().toISOString() }); } // Vercel Functions (any framework): functions/handler.js module.exports = async (req, res) => { // Set custom headers res.setHeader('X-Serverless-Function', 'true'); // Access environment variables const db = process.env.DATABASE_URL; // Return JSON response res.status(200).end(JSON.stringify({ method: req.method, path: req.url, environment: process.env.VERCEL_ENV })); }; // Function with configuration: functions/handler.json { "name": "my-function", "memory": 1024, "maxDuration": 10, "regions": ["iad1", "lon1"] } // Database connection with pooling // pages/api/data.js const { Pool } = require('pg'); let pool; if (process.env.VERCEL) { // Vercel: create new pool per invocation pool = new Pool({ connectionString: process.env.DATABASE_URL }); } else { // Local: reuse pool pool = new Pool({ connectionString: process.env.LOCAL_DATABASE_URL }); } export default async (req, res) => { const client = await pool.connect(); try { const result = await client.query('SELECT * FROM users'); res.json(result.rows); } finally { client.release(); // Vercel: close pool after request if (process.env.VERCEL) { await pool.end(); } } } - API Routes: Next.js
- Step 8
Edge Functions & Middleware
Run code at the Edge Network closest to users for ultra-low latency. Perfect for authentication, A/B testing, geo-routing, and personalization.
Edge features:
- Global Edge Network: 100+ locations worldwide
- Cold Start: Near-zero latency
- Middleware: Next.js middleware runs at edge
- Edge Config: Key-value store at the edge
// Next.js Middleware: middleware.js import { NextResponse } from 'next/server'; import { geolocation } from '@vercel/functions'; export function middleware(request) { // Get user's location at the edge const { country, city } = request.geo || geolocation(request); const response = NextResponse.next(); // Add custom headers response.headers.set('x-country', country || 'unknown'); response.headers.set('x-city', city || 'unknown'); // Geo-routing: redirect based on location if (country === 'IN') { return NextResponse.redirect(new URL('/in/home', request.url)); } // A/B testing at the edge const cohort = request.cookies.get('cohort') || 'a'; response.cookies.set('cohort', cohort.value); response.headers.set('x-cohort', cohort.value); return response; } export const config = { matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)' }; // Edge Function: functions/edge.js export default async (request) => { const url = new URL(request.url); // Parse request body const body = await request.json(); // Make external API call const response = await fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const data = await response.json(); return new Response(JSON.stringify({ success: true, data }), { headers: { 'Content-Type': 'application/json' } }); }; // Edge Config: fetch dynamic config at runtime // pages/api/recommendations.js import { getEdgeConfigContext, edgeConfig } from '@vercel/functions'; export default async (request) => { const ctx = getEdgeConfigContext(); const config = await edgeConfig('recommendations').get('default'); return new Response(JSON.stringify(config), { headers: { 'Content-Type': 'application/json' } }); }; - Step 9
Preview Deployments
Every pull request creates an isolated preview deployment with a unique URL. Share with stakeholders, test in production-like environment, and get automated feedback.
Preview deployment features:
- Unique URL: Each PR gets its own domain
- Preview Mode: Next.js draft mode integration
- Deployment Comments: Auto-comments on PRs
- Protected Deployments: Require approvals
# Enable automatic preview deployments # Vercel does this by default for Git-connected projects # Deploy specific branch to preview vercel --confirm # Creates preview deployment, outputs URL # Link PR to deployment (automatic with GitHub integration) # Vercel auto-comments on PRs with deployment URL # Enable Deployment Protection # 1. Go to Settings -> Deployment Protection # 2. Enable: # - Require all checks to pass # - Require deployment protection rules # - External review approval # Next.js Preview Mode // pages/api/auth/me.js import { setPreviewData } from '@vercel/og'; export default async (req, res) => { if (!req.query.token || req.query.token !== process.env.PREVIEW_SECRET) { return res.status(401).json({ message: 'Invalid token' }); } const { data } = await prisma.preview.findMany({ where: { published: false } }); res.setHeader('Content-Type', 'application/json'); res.write(JSON.stringify({ data })); res.end(); } // Enable preview mode in middleware export async function middleware(req) { const { previewData } = req.body; if (req.headers.get('x-prerender')) { return setPreviewData(previewData); } // ... rest of middleware } // Access preview deployment URL from environment const previewUrl = process.env.VERCEL_URL; if (previewUrl) { console.log(`Preview at: https://${previewUrl}`); } - Step 10
Custom Domains
Map your own domains to Vercel deployments. SSL is automatically provisioned and renewed via Let's Encrypt.
Domain features:
- Free SSL: Automatic HTTPS
- Multiple Domains: Map many domains per project
- Subdomains: Wildcard support
- DNS Management: Use Vercel or external DNS
# Add domain via Vercel Dashboard # 1. Go to Project Settings -> Domains # 2. Enter your domain (example.com) # 3. Verify ownership (DNS or email) # 4. Configure DNS (automatic if using Vercel DNS) # Configure DNS with Vercel (automatic SSL) # Vercel provides nameservers: # ns1.vercel-dns.com # ns2.vercel-dns.com # OR configure DNS externally # Add CNAME record: # www.example.com -> cname.example.com.vercel.app # Add A records for apex domain: # example.com -> 76.76.21.21 # example.com -> 76.76.21.22 # Verify SSL is active curl -I https://example.com # Should show: X-Proxy-Network-Operation: cache-MISSED # Wildcard subdomains # In Vercel Dashboard: # 1. Add *.example.com as domain # 2. Add wildcard CNAME: *.example.com -> cname.example.com.vercel.app # Deploy to specific domain vercel --prod --name my-site --domain example.com # Remove domain vercel remove-domain example.com - Step 11
Analytics and Monitoring
Vercel Analytics provides insights into web vitals, user metrics, and deployment performance. No additional instrumentation required.
Analytics features:
- Web Vitals: LCP, FID, CLS tracking
- User Metrics: Sessions, page views, unique users
- Performance: Deployment comparisons
- Geographic: User distribution by region
# Enable Analytics in Dashboard # 1. Go to Project Settings -> Analytics # 2. Toggle on for Pro/Teams (free for Hobby) # 3. Data appears within 24 hours # View analytics # - Real-time dashboard in Vercel UI # - Web Vitals scorecard # - Core Web Vitals: LCP, FID, CLS # - Request logs and error tracking # Analytics via API (Pro/Teams) export VERCEL_TOKEN="your-token" # Get analytics data curl -H "Authorization: Bearer $VERCEL_TOKEN" \ "https://api.vercel.com/v2/analytics/web-vitals?teamId=YOUR_TEAM_ID&projectId=YOUR_PROJECT_ID&startTime=2024-01-01&endTime=2024-01-31" # Common metrics endpoints: # - /analytics/web-vitals # - /analytics/users # - /analytics/sessions # - /analytics/pageviews # Next.js with Analytics component // components/Analytics.js import { Analytics } from '@vercel/analytics/react'; export default function AnalyticsComponent() { return <Analytics />; } // pages/_app.js import { Analytics } from '@vercel/analytics/react'; export default function App({ Component, pageProps }) { return ( <> <Component {...pageProps} /> <Analytics /> </> ); } // Track custom events // pages/index.js import useAnalytics from '@vercel/analytics/react'; export default function Page() { const analytics = useAnalytics(); const handleClick = () => { analytics('buttonClick', { button: 'subscribe' }); }; return <button onClick={handleClick}>Subscribe</button>; } - Step 12
Team Collaboration
Vercel Teams enable collaborative workflows with role-based access control, shared billing, and enterprise features.
Team features:
- Scopes: Organize projects into teams
- Roles: Admin, Member, Viewer
- Deployment Protection: Approval workflows
- SSO: SAML and SCIM integration
- Audit Logs: Track all actions
# Create a team (Pro/Teams plan) # 1. Go to vercel.com/new/team # 2. Enter team name and details # 3. Invite members via email # Add member to team # Dashboard: Settings -> Members -> Add Member # Roles: # - Admin: Full access # - Member: Deploy and configure # - Viewer: Read-only access # Deploy to team scope vercel --team team-slug # List team projects vercel ls --team team-slug # Set default team vercel --set-team team-slug # Enable deployment protection # Settings -> Deployment Protection -> # - Require approval from N people # - Block until all checks pass # - IP Access Rules # - Verified Committers # Enterprise features (Enterprise plan) # - SSO: Settings -> Single Sign-On # - Audit logs: Settings -> Audit Logs # - Advanced Security: Settings -> Security # - VPC Connection: Settings -> Network # CLI team management vercel teams ls # List teams vercel teams add team-slug # Add to team vercel teams rm team-slug # Remove from team - Step 13
Advanced Features
Explore advanced Vercel features for production-grade deployments.
Advanced topics:
- Edge Cache: Manual cache control
- Output Tracking: Deployments by output
- Incremental Static Regeneration: ISR for dynamic sites
- Vercel OG: Dynamic image generation
- Turbopack: Next.js fast build tool
// Incremental Static Regeneration (ISR) // pages/products/[id].js export async function getStaticProps({ params }) { const product = await fetchProduct(params.id); return { props: { product }, revalidate: 60 // Re-generate page every 60 seconds }; } // On-demand invalidation via API // pages/api/revalidate.js export default async (req, res) { if (req.query.token !== process.env.REVALIDATION_TOKEN) { return res.status(401).send('Invalid token'); } await res.revalidate(`/products/${req.query.id}`); res.send({ revalidated: true }); } // Vercel OG: Dynamic Image Generation // app/api/og/route.tsx import { ImageResponse } from '@vercel/og'; export async function GET(request: Request) { const { searchParams } = new URL(request.url); const title = searchParams.get('title') || 'My Image'; return new ImageResponse( ( <div tw="flex flex-col items-center justify-center h-full p-20 bg-gradient-to-br from-purple-500 to-pink-500"> <h1 tw="text-6xl font-bold text-white">{title}</h1> </div> ), { width: 1200, height: 630, headers: { 'Cache-Control': 'public, s-maxage=86400, immutable', } } ); } // Edge Cache Manual Control // pages/api/data.js export default function handler(req, res) { // Set cache for 1 hour at the edge res.setHeader('Cache-Control', 's-maxage=3600, stale-while-revalidate'); res.json({ data: 'cached' }); } // Force cache bypass res.setHeader('Cache-Control', 'no-cache, no-store'); // Turbopack (Next.js 14+) // package.json { "scripts": { "dev": "next dev --turbo", "build": "next build" } } // Custom build with Turbopack export default { experimental: { buildOutput: 'standalone' } }; - Step 14
Troubleshooting & Debugging
Common issues and debugging strategies for Vercel deployments.
Debugging tools:
- Deployment Logs: View build and runtime logs
- Function Logs: Serverless function output
- Verbose Build: Detailed build output
- Local Reproduction:
vercel devfor testing
# View deployment logs vercel logs <deployment-url> # View recent logs vercel logs --tail 50 # Follow logs in real-time vercel logs --follow # View function logs vercel logs function-name # Debug build errors # 1. View build logs in Dashboard -> Deployments -> [deployment] -> Logs # 2. Enable verbose build: # vercel.json: { "build": { "cmd": "npm run build 2>&1 | tee build.log" } } # Common issues and fixes: # Issue: Module not found # Fix: Check package.json dependencies npm install missing-package # Issue: Build timeout (10 min limit on Hobby) # Fix: Optimize build, use output tracking, or upgrade plan # Issue: Environment variables not set # Fix: Set in Dashboard -> Settings -> Environment Variables # Issue: Custom domain SSL not working # Fix: Wait up to 48 hours, verify DNS propagation # Issue: Functions cold start slow # Fix: Optimize imports, use Edge Functions, provisioned concurrency # Reproduce locally vercel dev # Runs with same configuration as production # Link local dev to production environment vercel dev --prod # Debug with --debug flag vercel deploy --debug - Step 15
Resources & Next Steps
Documentation:
- Vercel Docs
- CLI Reference
- REST API
- Deployment Configuration
- Serverless Functions
- Edge Functions
- Analytics
Learning:
- Vercel Learn - Free courses
- Next.js Learn - Full-stack course
- Vercel YouTube - Tutorials and talks
Community:
Integrations:
Next guides:
- Next.js on Vercel (deep dive)
- Vercel KV (serverless key-value store)
- Vercel Postgres (serverless PostgreSQL)
- Vercel AI SDK integration
- Vercel Security best practices
GitHub: https://github.com/vercel/vercel Official site: https://vercel.com Documentation: https://vercel.com/docs CLI Reference: https://vercel.com/docs/cli Vercel Learn: https://vercel.com/learn Community Forum: https://community.vercel.com/ Vercel Blog: https://vercel.com/blog Status: https://status.vercel.com/
Feature requests
Sign in to suggest features or vote on existing ones.
No feature requests yet.
Discussion
Sign in to join the discussion.
No comments yet.