Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Vercel
https://github.com/vercel/vercel
Admin
Vercel's Frontend Cloud provides the infrastructure and developer experience to build, scale, and
...
Tokens:
111,619
Snippets:
1,065
Trust Score:
10
Update:
3 weeks ago
Context
Skills
Chat
Benchmark
83.7
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Vercel CLI & Build SDK Vercel is a unified platform for building and deploying modern web applications. This monorepo contains the Vercel CLI, build runtimes, and serverless function infrastructure that powers deployments to Vercel's edge network. The platform supports multiple languages and frameworks including Node.js, Python, Go, and Ruby with first-class support for popular frameworks like Next.js, Express, Fastify, and more. The core functionality revolves around three main areas: the CLI for deploying and managing projects, the build-utils package for creating custom runtimes and serverless functions, and the functions package for accessing Vercel-specific features like geolocation, caching, and middleware. These tools enable developers to build serverless applications that scale automatically and deploy globally with minimal configuration. ## Vercel CLI - Deploy Projects The Vercel CLI provides commands for deploying, managing, and developing projects locally. It handles authentication, project linking, environment variables, and deployment orchestration. ```bash # Install Vercel CLI globally npm install -g vercel # Login to your Vercel account vercel login # Deploy current directory to production vercel --prod # Deploy with specific scope/team vercel --scope my-team # Run local development server vercel dev # Pull environment variables from Vercel vercel env pull .env.local # Link local project to Vercel project vercel link # List recent deployments vercel list # View deployment logs vercel logs <deployment-url> # Manage environment variables vercel env add MY_SECRET production vercel env rm MY_SECRET production vercel env ls # Build project locally (same as Vercel build) vercel build # Inspect deployment details vercel inspect <deployment-url> ``` ## @vercel/build-utils - Create Serverless Functions The build-utils package provides utilities for creating custom runtimes and serverless functions. It includes file handling, Lambda creation, dependency management, and build orchestration tools. ```typescript import { createLambda, download, glob, FileBlob, FileFsRef, getNodeVersion, runNpmInstall, runPackageJsonScript, Lambda, BuildOptions, } from '@vercel/build-utils'; // Create a simple Lambda function const lambda = await createLambda({ runtime: 'nodejs20.x', handler: 'index.handler', files: { 'index.js': new FileBlob({ data: ` exports.handler = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: 'Hello from Lambda!' }) }; }; ` }), }, }); // Build function implementation for custom runtime export async function build({ files, entrypoint, workPath, config, meta }: BuildOptions) { // Download source files to working directory const downloadedFiles = await download(files, workPath, meta); // Get appropriate Node.js version const nodeVersion = await getNodeVersion(workPath, undefined, config, meta); // Install dependencies await runNpmInstall(workPath, [], {}, meta); // Run build script if present await runPackageJsonScript(workPath, ['vercel-build', 'build'], {}); // Collect output files const outputFiles = await glob('**', workPath); // Create Lambda from compiled files const lambda = new Lambda({ files: outputFiles, handler: 'index.handler', runtime: nodeVersion.runtime, maxDuration: config.maxDuration, memory: config.memory, regions: ['iad1'], supportsResponseStreaming: true, }); return { output: lambda }; } // Prepare cache for faster subsequent builds export async function prepareCache({ workPath, repoRootPath }) { const cache = await glob('node_modules/**', workPath); return cache; } ``` ## @vercel/functions - Geolocation and IP Address The functions package provides utilities for accessing request metadata including client IP address and geolocation data from Vercel's edge network headers. ```typescript import { geolocation, ipAddress, Geo } from '@vercel/functions'; export function GET(request: Request) { // Get client IP address from x-real-ip header const ip = ipAddress(request); // Get full geolocation data const geo: Geo = geolocation(request); // Geo object contains: // { // city: "New York", // country: "US", // flag: "🇺🇸", // countryRegion: "NY", // region: "iad1", // latitude: "40.7128", // longitude: "-74.0060", // postalCode: "10001" // } return Response.json({ ip, location: geo, greeting: `Hello visitor from ${geo.city}, ${geo.country}!` }); } // Works with any request object that has headers export function middleware(request: Request) { const country = geolocation(request).country; if (country === 'US') { return Response.redirect('/us'); } return Response.redirect('/global'); } ``` ## @vercel/functions - waitUntil for Background Tasks The waitUntil function extends the request handler lifetime to complete background tasks after sending the response, useful for logging, analytics, and async operations. ```typescript import { waitUntil } from '@vercel/functions'; export async function GET(request: Request) { // Start background task that continues after response waitUntil( fetch('https://analytics.example.com/track', { method: 'POST', body: JSON.stringify({ event: 'page_view', path: request.url }) }) ); // Response returns immediately return new Response('OK'); } // Multiple background tasks export async function POST(request: Request) { const data = await request.json(); // Queue multiple async operations waitUntil(saveToDatabase(data)); waitUntil(sendNotification(data)); waitUntil(updateCache(data)); return Response.json({ success: true }); } // Error handling in background tasks waitUntil( (async () => { try { await riskyOperation(); } catch (error) { console.error('Background task failed:', error); } })() ); ``` ## @vercel/edge - Middleware Rewrite and Next The edge package provides middleware utilities for rewriting requests and continuing the middleware chain with modified headers or response options. ```typescript import { rewrite, next } from '@vercel/edge'; // Rewrite requests to different paths export default async function middleware(request: Request) { const url = new URL(request.url); // A/B testing with rewrites if (Math.random() > 0.5) { url.pathname = `/experiment-a${url.pathname}`; return rewrite(url); } return rewrite(new URL('/experiment-b' + url.pathname, request.url)); } // Continue with modified request headers export default function middleware(request: Request) { const newHeaders = new Headers(request.headers); newHeaders.set('x-user-id', 'user_123'); newHeaders.delete('authorization'); return rewrite(request.url, { request: { headers: newHeaders } }); } // Add response headers and continue export default function middleware(_request: Request) { return next({ headers: { 'x-from-middleware': 'true', 'x-custom-header': 'value' } }); } // JWT authentication middleware export default function middleware(request: Request) { const auth = verifyJwt(request.headers.get('Authorization')); if (!auth.valid) { return rewrite(new URL('/api/unauthorized', request.url)); } // Pass user ID to downstream functions const url = new URL(request.url); url.searchParams.set('_userId', auth.userId); return rewrite(url); } export const config = { matcher: '/api/:path*' }; ``` ## @vercel/functions - Cache Invalidation Functions for programmatic cache invalidation by tag or source image, allowing fine-grained control over cached content. ```typescript import { invalidateByTag, dangerouslyDeleteByTag, invalidateBySrcImage, dangerouslyDeleteBySrcImage } from '@vercel/functions'; // Invalidate cache entries by tag (soft invalidation) export async function POST(request: Request) { const { productId } = await request.json(); // Invalidate single tag await invalidateByTag(`product-${productId}`); // Invalidate multiple tags at once await invalidateByTag(['products', 'homepage', `category-${categoryId}`]); return Response.json({ revalidated: true }); } // Hard delete cached entries (use with caution) export async function DELETE(request: Request) { const { tag } = await request.json(); await dangerouslyDeleteByTag(tag, { // Optional configuration }); return Response.json({ deleted: true }); } // Invalidate optimized images by source URL export async function revalidateImages() { await invalidateBySrcImage('/images/hero.jpg'); // Multiple images await invalidateBySrcImage([ '/images/product-1.jpg', '/images/product-2.jpg' ]); } ``` ## Custom Runtime Development Create custom runtimes for new languages by implementing the Runtime interface with build, prepareCache, shouldServe, and startDevServer functions. ```typescript // runtime/index.ts import { spawn } from 'child_process'; import { BuildOptions, createLambda, download, glob, StartDevServerOptions, ShouldServeOptions } from '@vercel/build-utils'; // Required: Runtime API version export const version = 3; // Required: Build function that creates Lambda export async function build({ files, entrypoint, workPath, config, meta }: BuildOptions) { // Download source files await download(files, workPath, meta); // Compile/process your language await compileMyLanguage(workPath, entrypoint); // Collect compiled output const outputFiles = await glob('**', workPath); const lambda = await createLambda({ files: outputFiles, handler: entrypoint.replace(/\.mylang$/, '.handler'), runtime: 'provided.al2023', architecture: 'arm64', }); return { output: lambda }; } // Optional: Cache dependencies between builds export async function prepareCache({ workPath, repoRootPath }) { return await glob('**/deps/**', workPath); } // Optional: Control which requests the runtime handles in dev export async function shouldServe({ requestPath, entrypoint }: ShouldServeOptions) { return requestPath === entrypoint; } // Optional: Custom dev server for faster local development export async function startDevServer({ entrypoint }: StartDevServerOptions) { const child = spawn('my-runtime-dev-server', [entrypoint], { stdio: ['ignore', 'inherit', 'inherit', 'pipe'], }); // Read port from child process const port = await new Promise<number>(resolve => { child.stdio[3].setEncoding('utf8'); child.stdio[3].once('data', data => resolve(Number(data))); }); return { pid: child.pid, port }; } ``` ## @vercel/routing-utils - Route Configuration Utilities for normalizing and transforming route configurations including redirects, rewrites, headers, and clean URLs. ```typescript import { normalizeRoutes, getTransformedRoutes, isHandler, Route } from '@vercel/routing-utils'; // Normalize raw route configuration const { routes, error } = normalizeRoutes([ { src: '/old-path', dest: '/new-path' }, { src: '/api/(.*)', dest: '/api/$1', headers: { 'x-api': 'true' } }, { handle: 'filesystem' }, { src: '/(.*)', dest: '/index.html' }, ]); if (error) { console.error('Invalid routes:', error.message); } // Transform vercel.json config to normalized routes const config = { cleanUrls: true, trailingSlash: false, redirects: [ { source: '/blog/:slug', destination: '/posts/:slug', permanent: true } ], rewrites: [ { source: '/api/:path*', destination: 'https://api.example.com/:path*' } ], headers: [ { source: '/(.*)', headers: [ { key: 'X-Frame-Options', value: 'DENY' } ] } ] }; const { routes: transformedRoutes, error: transformError } = getTransformedRoutes(config); // Check route types routes?.forEach((route: Route, index) => { if (isHandler(route)) { console.log(`Handler at ${index}: ${route.handle}`); } else { console.log(`Route at ${index}: ${route.src} -> ${route.dest}`); } }); ``` ## Lambda Configuration Options Configure Lambda functions with memory, duration, regions, streaming, and architecture settings for optimal performance. ```typescript import { Lambda, NodejsLambda } from '@vercel/build-utils'; // Full Lambda configuration const lambda = new Lambda({ files: outputFiles, handler: 'api/handler.main', runtime: 'nodejs20.x', // Resource configuration memory: 1024, // MB maxDuration: 30, // seconds, or 'max' for plan limit architecture: 'arm64', // or 'x86_64' // Regional deployment regions: ['iad1', 'sfo1', 'cdg1'], functionFailoverRegions: ['iad1'], // Response streaming for large responses supportsResponseStreaming: true, // Environment variables environment: { NODE_ENV: 'production', DATABASE_URL: process.env.DATABASE_URL, }, // Query string passthrough allowQuery: ['page', 'limit', 'sort'], // Framework metadata framework: { slug: 'nextjs', version: '14.0.0' }, // Operation type for observability operationType: 'API', }); // Node.js specific Lambda with helpers const nodejsLambda = new NodejsLambda({ files: outputFiles, handler: 'index.handler', runtime: 'nodejs20.x', shouldAddHelpers: true, // Add Vercel request helpers shouldAddSourcemapSupport: true, useWebApi: true, // Use Web API Request/Response }); ``` ## vercel.json Configuration Configure project settings, functions, routes, and build options via vercel.json at the project root. ```json { "version": 2, "buildCommand": "npm run build", "installCommand": "npm install", "outputDirectory": "dist", "framework": "nextjs", "functions": { "api/**/*.ts": { "memory": 1024, "maxDuration": 30, "regions": ["iad1"] }, "api/heavy-compute.ts": { "memory": 3008, "maxDuration": 60 } }, "routes": [ { "src": "/api/(.*)", "dest": "/api/$1" }, { "handle": "filesystem" }, { "src": "/(.*)", "dest": "/index.html" } ], "redirects": [ { "source": "/old", "destination": "/new", "permanent": true } ], "rewrites": [ { "source": "/proxy/:path*", "destination": "https://api.example.com/:path*" } ], "headers": [ { "source": "/(.*)", "headers": [ { "key": "X-Content-Type-Options", "value": "nosniff" }, { "key": "X-Frame-Options", "value": "DENY" } ] } ], "cleanUrls": true, "trailingSlash": false, "env": { "API_URL": "@api-url" }, "build": { "env": { "NODE_ENV": "production" } } } ``` ## Express/Fastify/Hono Framework Adapters Vercel provides runtime adapters for popular Node.js frameworks, enabling seamless deployment of existing applications as serverless functions. ```typescript // Express application (api/index.ts) import express from 'express'; const app = express(); app.use(express.json()); app.get('/api/users', (req, res) => { res.json([{ id: 1, name: 'John' }]); }); app.post('/api/users', (req, res) => { const user = req.body; res.status(201).json({ id: 2, ...user }); }); export default app; // Fastify application (api/index.ts) import Fastify from 'fastify'; const app = Fastify({ logger: true }); app.get('/api/health', async () => { return { status: 'ok' }; }); app.post('/api/data', async (request, reply) => { return { received: request.body }; }); export default async (req, res) => { await app.ready(); app.server.emit('request', req, res); }; // Hono application (api/index.ts) import { Hono } from 'hono'; import { handle } from 'hono/vercel'; const app = new Hono().basePath('/api'); app.get('/hello', (c) => c.json({ message: 'Hello Hono!' })); app.post('/echo', async (c) => { const body = await c.req.json(); return c.json(body); }); export default handle(app); ``` The Vercel platform provides a comprehensive solution for building, deploying, and scaling modern web applications. The CLI enables seamless deployment workflows while the build-utils package allows creation of custom runtimes for any language. The functions package gives access to edge network features like geolocation and caching, making it easy to build globally distributed applications. Integration patterns typically involve using the CLI for deployment automation in CI/CD pipelines, leveraging the functions package for request enrichment and middleware logic, and configuring vercel.json for advanced routing and function settings. Framework adapters simplify migration of existing Express, Fastify, or Hono applications to serverless, while custom runtimes enable support for additional languages and build systems. The platform's focus on developer experience means most applications can deploy with zero configuration, scaling automatically based on traffic.