Next.js Deployment on Vercel — Complete Guide
Advertisement
Next.js Deployment on Vercel — Complete Guide
Vercel is the official Next.js hosting platform, providing seamless deployment with edge functions, serverless functions, and automatic optimizations.
- Next.js Deployment on Vercel — Complete Guide
- Prepare Your Project
- Deploy to Vercel
- Via Vercel CLI
- Via Web Dashboard
- Environment Variables
- Configuration File
- Optimize for Production
- Build Command
- Start Command
- Custom Domains
- Example: Adding Domain
- Environment-Specific Deployments
- Monitoring and Analytics
- Real User Monitoring
- Speed Insights
- Database Connection Pooling
- Serverless Functions
- Cron Jobs
- Edge Middleware
- Pre-render Pages
- Deployment Checklist
- Rollback Strategy
- Real-World: Full Stack Deployment
- FAQ
Prepare Your Project
Ensure your project is git-ready:
# Initialize git if needed
git init
git add .
git commit -m "Initial commit"
# Push to GitHub, GitLab, or Bitbucket
git push origin main
Deploy to Vercel
Via Vercel CLI
npm i -g vercel
vercel
Follow prompts to connect your account and deploy.
Via Web Dashboard
- Go to vercel.com
- Sign in or create account
- Import your Git repository
- Configure project settings
- Deploy
Environment Variables
Set environment variables in Vercel dashboard:
DATABASE_URL=postgresql://...
NEXTAUTH_SECRET=your_secret
NEXTAUTH_URL=https://yourdomain.com
API_KEY=your_api_key
Or in vercel.json:
{
"env": {
"DATABASE_URL": "@database_url",
"NEXTAUTH_SECRET": "@nextauth_secret"
}
}
Configuration File
Create vercel.json for advanced settings:
{
"buildCommand": "npm run build",
"devCommand": "npm run dev",
"installCommand": "npm ci",
"framework": "nextjs",
"regions": ["iad1"],
"functions": {
"api/**/*.ts": {
"memory": 3008,
"maxDuration": 60
}
},
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Cache-Control", "value": "no-store" }
]
}
]
}
Optimize for Production
Build Command
npm run build
This creates optimized production build in .next/.
Start Command
npm run start
Runs production server locally for testing.
Custom Domains
- Go to project settings in Vercel dashboard
- Add domain
- Update DNS records (or transfer domain to Vercel)
Example: Adding Domain
yourdomain.com → CNAME → cname.vercel-dns.com
Environment-Specific Deployments
Deploy to different environments:
main branch → Production
staging branch → Staging
development branch → Preview
Configure in Vercel project settings.
Monitoring and Analytics
Real User Monitoring
// app/layout.tsx
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
Speed Insights
import { SpeedInsights } from '@vercel/speed-insights/next'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<SpeedInsights />
</body>
</html>
)
}
Database Connection Pooling
Use connection pooling for databases:
// lib/prisma.ts with pooling
import { PrismaClient } from '@prisma/client'
const prismaClientSingleton = () => {
return new PrismaClient({
log: ['error', 'warn']
})
}
declare global {
var prisma: undefined | ReturnType<typeof prismaClientSingleton>
}
const prisma = global.prisma ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') global.prisma = prisma
Serverless Functions
Configure function memory and duration:
{
"functions": {
"api/ai/**/*.ts": {
"memory": 3008,
"maxDuration": 120
},
"api/webhooks/**/*.ts": {
"memory": 512,
"maxDuration": 30
}
}
}
Cron Jobs
Schedule background tasks:
{
"crons": [
{
"path": "/api/cron/cleanup",
"schedule": "0 0 * * *"
},
{
"path": "/api/cron/sync",
"schedule": "*/5 * * * *"
}
]
}
// app/api/cron/cleanup/route.ts
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
// Verify request is from Vercel
const authHeader = request.headers.get('authorization')
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Perform cleanup
await db.sessions.deleteMany({
where: { expiresAt: { lt: new Date() } }
})
return NextResponse.json({ success: true })
}
Edge Middleware
Deploy middleware to Vercel Edge Network:
// middleware.ts - automatically deployed to edge
export function middleware(request) {
const response = NextResponse.next()
response.headers.set('X-Custom-Header', 'value')
return response
}
export const config = {
matcher: ['/protected/:path*']
}
Pre-render Pages
Generate static pages at build time:
// app/blog/[slug]/page.tsx
export async function generateStaticParams() {
const posts = await db.posts.findMany()
return posts.map(post => ({ slug: post.slug }))
}
export const revalidate = 3600 // ISR
export default async function PostPage({ params }) {
const post = await db.posts.findUnique({
where: { slug: params.slug }
})
return <article>{post.content}</article>
}
Deployment Checklist
- Environment variables set
- Database migrations applied
- Build succeeds:
npm run build - No console errors in production
- Images optimized with next/image
- Fonts optimized with next/font
- Meta tags configured
- Error pages created
- Robots.txt and sitemap.xml present
- Analytics configured
- Backups configured
- SSL certificate valid
- Monitoring set up
Rollback Strategy
# View deployments
vercel deployments
# Promote previous deployment
vercel promote <deployment-url>
Real-World: Full Stack Deployment
// vercel.json
{
"buildCommand": "npm run build",
"devCommand": "npm run dev",
"framework": "nextjs",
"regions": ["iad1", "sfo1"],
"env": {
"DATABASE_URL": "@database_url",
"NEXTAUTH_SECRET": "@nextauth_secret",
"NEXTAUTH_URL": "https://yourdomain.com"
},
"functions": {
"api/**/*.ts": {
"memory": 3008,
"maxDuration": 60
}
},
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Cache-Control", "value": "no-store" }
]
},
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" }
]
}
]
}
FAQ
Q: Can I deploy Next.js anywhere besides Vercel? A: Yes, any Node.js host (AWS, Heroku, DigitalOcean, etc.). Vercel optimizes for Next.js.
Q: How do I set up CI/CD? A: Vercel automatically deploys on git push. GitHub Actions can run tests before Vercel deploy.
Q: What's the difference between Serverless and Edge functions? A: Serverless is globally distributed but 1-10 second cold start. Edge is very fast but limited memory.
Vercel deployment ensures your Next.js app runs at peak performance globally.
Advertisement