Master Vercel deployments for Next.js applications. Learn edge functions, caching strategies, environment variables, preview deployments, analytics, and performance optimization for production.
# Vercel Deployment Optimization Guide
Optimize your Next.js application deployments on Vercel with advanced caching, edge functions, and performance tuning strategies.
## Vercel Configuration
### vercel.json Setup
```json
{
"buildCommand": "npm run build",
"outputDirectory": ".next",
"framework": "nextjs",
"regions": ["iad1", "sfo1", "fra1"],
"functions": {
"app/api/**/*.ts": {
"memory": 1024,
"maxDuration": 30
},
"app/api/heavy-computation/route.ts": {
"memory": 3008,
"maxDuration": 60
}
},
"crons": [
{
"path": "/api/cron/cleanup",
"schedule": "0 0 * * *"
},
{
"path": "/api/cron/sync-data",
"schedule": "*/15 * * * *"
}
],
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Origin", "value": "*" },
{ "key": "Access-Control-Allow-Methods", "value": "GET,POST,PUT,DELETE,OPTIONS" }
]
},
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "DENY" },
{ "key": "X-XSS-Protection", "value": "1; mode=block" }
]
}
],
"rewrites": [
{ "source": "/blog/:slug", "destination": "/posts/:slug" },
{ "source": "/api/v1/:path*", "destination": "/api/:path*" }
]
}
```
## Edge Runtime Optimization
### Edge API Routes
```typescript
// app/api/edge/route.ts
import { NextRequest } from "next/server";
export const runtime = "edge";
export const preferredRegion = ["iad1", "fra1", "hnd1"];
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const country = request.geo?.country || "US";
const city = request.geo?.city || "Unknown";
// Edge-optimized response
return new Response(
JSON.stringify({
message: `Hello from the edge!`,
location: { country, city },
timestamp: Date.now(),
}),
{
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, s-maxage=60, stale-while-revalidate=300",
},
}
);
}
```
### Edge Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|public/).*)",
],
};
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Add performance headers
response.headers.set("X-Request-Id", crypto.randomUUID());
response.headers.set("X-Response-Time", Date.now().toString());
// Geo-based routing
const country = request.geo?.country || "US";
if (country === "CN") {
return NextResponse.redirect(new URL("/cn", request.url));
}
// Bot detection
const userAgent = request.headers.get("user-agent") || "";
if (/bot|crawler|spider/i.test(userAgent)) {
response.headers.set("X-Robots-Tag", "noindex");
}
// A/B testing
const bucket = Math.random() < 0.5 ? "control" : "variant";
response.cookies.set("ab-bucket", bucket, { maxAge: 86400 });
return response;
}
```
## Caching Strategies
### ISR Configuration
```typescript
// app/posts/[slug]/page.tsx
import { notFound } from "next/navigation";
export const revalidate = 3600; // Revalidate every hour
export async function generateStaticParams() {
const posts = await fetchAllPosts();
return posts.map((post) => ({ slug: post.slug }));
}
export default async function PostPage({ params }: { params: { slug: string } }) {
const post = await fetchPost(params.slug);
if (!post) notFound();
return <PostContent post={post} />;
}
```
### API Route Caching
```typescript
// app/api/data/route.ts
import { NextResponse } from "next/server";
export async function GET() {
const data = await fetchData();
return NextResponse.json(data, {
headers: {
// CDN cache for 60s, allow stale for 5 min while revalidating
"Cache-Control": "public, s-maxage=60, stale-while-revalidate=300",
// Vary by authorization for personalized responses
"Vary": "Authorization",
// CDN cache tag for targeted invalidation
"Cache-Tag": "data-api",
},
});
}
```
## Environment Variables
### Environment Configuration
```typescript
// lib/env.ts
import { z } from "zod";
const envSchema = z.object({
DATABASE_URL: z.string().url(),
NEXTAUTH_SECRET: z.string().min(32),
NEXTAUTH_URL: z.string().url(),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
OPENAI_API_KEY: z.string().startsWith("sk-"),
VERCEL_ENV: z.enum(["production", "preview", "development"]).default("development"),
VERCEL_URL: z.string().optional(),
});
export const env = envSchema.parse(process.env);
// Dynamic base URL
export function getBaseUrl() {
if (typeof window !== "undefined") return "";
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
return `http://localhost:${process.env.PORT ?? 3000}`;
}
```
## Preview Deployments
### Preview-Specific Configuration
```typescript
// app/layout.tsx
import { headers } from "next/headers";
export default function RootLayout({ children }: { children: React.ReactNode }) {
const isPreview = process.env.VERCEL_ENV === "preview";
return (
<html lang="en">
<body>
{isPreview && (
<div className="fixed top-0 left-0 right-0 bg-yellow-400 text-black text-center py-1 text-sm z-50">
Preview Deployment - {process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7)}
</div>
)}
{children}
</body>
</html>
);
}
```
## Analytics and Monitoring
### Web Vitals Reporting
```typescript
// app/layout.tsx
import { Analytics } from "@vercel/analytics/react";
import { SpeedInsights } from "@vercel/speed-insights/next";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Analytics />
<SpeedInsights />
</body>
</html>
);
}
```
### Custom Web Vitals
```typescript
// lib/vitals.ts
import { onCLS, onFID, onLCP, onFCP, onTTFB } from "web-vitals";
export function reportWebVitals() {
onCLS(sendToAnalytics);
onFID(sendToAnalytics);
onLCP(sendToAnalytics);
onFCP(sendToAnalytics);
onTTFB(sendToAnalytics);
}
function sendToAnalytics(metric: { name: string; value: number; id: string }) {
fetch("/api/analytics/vitals", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: metric.name,
value: metric.value,
id: metric.id,
url: window.location.pathname,
}),
});
}
```
## Build Optimization
### next.config.js
```javascript
// next.config.js
/** @type {import("next").NextConfig} */
const nextConfig = {
experimental: {
optimizeCss: true,
optimizePackageImports: ["lucide-react", "@radix-ui/react-icons"],
},
images: {
remotePatterns: [
{ protocol: "https", hostname: "**.supabase.co" },
{ protocol: "https", hostname: "images.unsplash.com" },
],
formats: ["image/avif", "image/webp"],
},
logging: {
fetches: { fullUrl: true },
},
poweredByHeader: false,
compress: true,
};
module.exports = nextConfig;
```
This complete Vercel optimization guide covers edge functions, caching, environment management, preview deployments, and performance monitoring for production-ready applications.This vercel prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their vercel implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For vercel projects, consider mentioning your framework version, coding style, and any specific libraries you're using.