Deploy and optimize Next.js apps on Vercel with serverless functions, edge functions, and advanced caching.
# Next.js Serverless & Vercel Deployment
Master serverless deployment with Next.js and Vercel using Google Antigravity IDE. This comprehensive guide covers edge functions, environment configuration, and production optimization.
## Why Vercel Serverless?
Vercel provides optimal Next.js deployment with automatic scaling. Google Antigravity IDE's Gemini 3 engine suggests deployment configurations and performance optimizations.
## Project Configuration
```json
// vercel.json
{
"framework": "nextjs",
"regions": ["iad1", "sfo1", "cdg1"],
"functions": {
"app/api/**/*.ts": {
"maxDuration": 30,
"memory": 1024
}
},
"headers": [
{
"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": "/api/:path*", "destination": "/api/:path*" }
],
"crons": [
{
"path": "/api/cron/cleanup",
"schedule": "0 0 * * *"
}
]
}
```
## Edge Functions
```typescript
// app/api/geo/route.ts
import { NextRequest } from "next/server";
export const runtime = "edge";
export const preferredRegion = ["iad1", "sfo1", "cdg1"];
export async function GET(request: NextRequest) {
const geo = request.geo;
const ip = request.ip;
return Response.json({
ip,
country: geo?.country,
city: geo?.city,
region: geo?.region,
latitude: geo?.latitude,
longitude: geo?.longitude,
});
}
// Middleware for edge routing
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const country = request.geo?.country || "US";
// Country-based routing
if (country === "DE" || country === "FR") {
return NextResponse.rewrite(new URL("/eu", request.url));
}
// A/B testing
const bucket = Math.random() < 0.5 ? "control" : "experiment";
const response = NextResponse.next();
response.cookies.set("ab-bucket", bucket);
return response;
}
export const config = {
matcher: ["/((?!api|_next/static|favicon.ico).*)"],
};
```
## Environment Configuration
```typescript
// lib/env.ts
import { z } from "zod";
const envSchema = z.object({
// Server-only
DATABASE_URL: z.string().url(),
NEXTAUTH_SECRET: z.string().min(32),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
// Public (NEXT_PUBLIC_ prefix)
NEXT_PUBLIC_APP_URL: z.string().url(),
NEXT_PUBLIC_STRIPE_KEY: z.string().startsWith("pk_"),
});
type Env = z.infer<typeof envSchema>;
function validateEnv(): Env {
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
console.error("Invalid environment variables:", parsed.error.flatten());
throw new Error("Invalid environment variables");
}
return parsed.data;
}
export const env = validateEnv();
```
## Serverless API Routes
```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
export async function GET(request: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const searchParams = request.nextUrl.searchParams;
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "20");
const users = await prisma.user.findMany({
skip: (page - 1) * limit,
take: limit,
select: {
id: true,
name: true,
email: true,
createdAt: true,
},
});
return NextResponse.json({ data: users, page, limit });
}
// Cron job endpoint
// app/api/cron/cleanup/route.ts
import { NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const authHeader = request.headers.get("authorization");
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
// Cleanup logic
const deleted = await prisma.session.deleteMany({
where: {
expires: { lt: new Date() },
},
});
return Response.json({ deleted: deleted.count });
}
```
## Build Optimization
```typescript
// next.config.ts
import type { NextConfig } from "next";
import bundleAnalyzer from "@next/bundle-analyzer";
const withBundleAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === "true",
});
const nextConfig: NextConfig = {
output: "standalone",
experimental: {
optimizePackageImports: ["@/components/ui"],
},
images: {
remotePatterns: [
{ protocol: "https", hostname: "**.cloudinary.com" },
],
},
async headers() {
return [
{
source: "/:path*",
headers: [
{ key: "X-DNS-Prefetch-Control", value: "on" },
],
},
];
},
};
export default withBundleAnalyzer(nextConfig);
```
## Best Practices
- Use Edge Runtime for low-latency responses
- Configure proper environment validation
- Implement cron jobs for maintenance
- Apply regional deployment for performance
- Monitor with Vercel Analytics
- Use preview deployments for testing
Google Antigravity IDE provides Vercel deployment templates and automatically suggests optimal configurations for serverless Next.js applications.This Next.js 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 next.js 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 Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.