🚀 How to Migrate From Vercel to Hetzner Using Blob Storage and Neon PostgreSQL: The Complete Step-by-Step Guide
By @george ·

🚀 How to Migrate From Vercel to Hetzner Using Blob Storage and Neon PostgreSQL: The Complete Step-by-Step Guide
Learning how to migrate from Vercel to Hetzner using Blob storage and Neon PostgreSQL is one of the highest-ROI infrastructure moves a growing engineering team or indie SaaS founder can make. Vercel’s developer experience is legendary when you are launching an MVP—push to `main`, get a global preview URL in forty seconds, and never think about Nginx. Yet the moment a content-heavy Next.js app, media-rich SaaS, or multi-developer team starts scaling past hobby limits, serverless usage meters—per-seat fees, Fast Data Transfer overages, Image Optimization transformations, and Blob origin-transfer charges—quietly turn a **$20/month** starting bill into **$200 to $500+ per month**. 💸
The biggest mistake developers make when leaving Vercel is trying to self-host *everything* at once—ripping out their managed database, writing raw Nginx configs by hand, and risking catastrophic data loss just to save money. There is a vastly smarter architecture: **move your compute and static/media delivery to a hardened Hetzner Cloud VPS running Coolify (or Dokploy) + S3-compatible Blob storage, while keeping your database on Neon PostgreSQL.** You slash monthly hosting costs by **70% to 85%**, gain predictable flat-rate bandwidth (up to 20 TB/month included in EU regions), eliminate serverless cold starts, and *keep* Neon’s zero-downtime branching, automated backups, and point-in-time recovery. 🛠️
This step-by-step engineering playbook walks through the exact 2026 pricing math, region-pairing latency rules, Blob storage refactoring, production multi-stage Dockerfiles, zero-downtime Neon pooling configuration, and instant-rollback DNS cutover.
💰 The 2026 Cost & Architecture Reality Check
Even after Hetzner’s mid-2026 price adjustments, the price-to-performance gap between usage-metered serverless platforms and dedicated/shared European or US VPS compute remains staggering. Compare a realistic growing SaaS stack (3 developers, 2 TB monthly transfer, 500 GB media storage, 10M+ requests, PostgreSQL database):
| Infrastructure Layer | Vercel Pro + Vercel Blob + Neon | Hetzner Cloud + S3 Object Storage + Neon | Monthly Savings |
| --- | --- | --- | --- |
| **App Compute & Team Seats** | **$60/mo** (3 seats × $20) + compute overages | **€8.49/mo (~$9.50)** for **Hetzner CX33** (4 vCPU, 8 GB RAM, 80 GB NVMe) + **$0** Coolify/Dokploy | **~$50+/mo saved** |
| **Bandwidth / Egress (2 TB)** | 1 TB included + **$150–$400/mo** overage ($0.15/GB–$400/TB) | **€0** (up to **20 TB free egress** on EU Hetzner VPS; Cloudflare CDN in front) | **$150–$400/mo saved** |
| **Blob / Media Storage (500 GB + 1 TB egress)** | ~$12–$20 storage + **$50–$110** transfer/origin/ops fees | **€6.49/mo (~$7.20)** **Hetzner Object Storage** (1 TB storage + 1 TB egress + free API calls) *or* **Cloudflare R2** (~$7.50 storage, **$0 egress**) | **$55–$120/mo saved** |
| **Managed Database (Neon PostgreSQL)** | **~$15–$25/mo** (Launch/usage tier) | **~$15–$25/mo** (same Neon project—zero DB migration risk!) | $0 (risk avoided) |
| **Automated Backups & Monitoring** | Add-on log drains | **€1.70/mo** Hetzner automated backups + free Uptime Kuma / Better Stack | Predictable flat rate |
| **Estimated Monthly Total** | **~$285 – $550+ / month** | **~$35 – $48 / month** | **~85% Cost Reduction** |
🌍 The Golden Latency Rule: Pair Your Hetzner & Neon Regions!
Before provisioning a single server, check your **Neon PostgreSQL region** inside the Neon Console. One of the most common self-hosting disasters happens when a developer spins up a cheap Hetzner box in Helsinki (`hel1`) while their Neon database sits in AWS `us-east-1` (Virginia)—adding **115 to 130 milliseconds of transatlantic round-trip latency to every single SQL query**! If a Server Component executes 6 sequential queries, you just added 750 ms of dead air to every page load.
Always match regions tightly:
- **European Stack:** Pair **Hetzner Falkenstein (`fsn1`)** or **Nuremberg (`nbg1`)** with **Neon `aws-eu-central-1` (Frankfurt)** → **~4 to 7 ms RTT**.
- **US East Stack:** Pair **Hetzner Ashburn (`ash`)** with **Neon `aws-us-east-1` (N. Virginia)** → **~2 to 5 ms RTT**.
- **US West Stack:** Pair **Hetzner Hillsboro (`hil`)** with **Neon `aws-us-west-2` (Oregon)** → **~3 to 6 ms RTT**. ⚡
🔍 Phase 1: Pre-Migration Codebase Audit (Exposing Hidden Vercel Lock-In)
Before touching DNS or servers, grep your repository for four Vercel-specific features that behave differently inside a persistent Docker container:
- **Next.js Output Mode (`next.config.mjs`):** Enable `output: 'standalone'`. This instructs Next.js to trace only the exact files needed at runtime and output a self-contained `.next/standalone` bundle—shrinking your final Docker image from **1.4 GB down to ~140 MB**!
- **Edge Runtime Routes (`export const runtime = 'edge'`):** Remove `runtime = 'edge'` on API routes and pages unless strictly necessary, switching cleanly to standard Node.js runtime (`nodejs`) so you have full access to native TCP sockets, `sharp`, and `pg` connection pools.
- **Vercel Cron Jobs (`vercel.json`):** Vercel’s `crons` array will not fire on Hetzner. Map every scheduled endpoint (e.g., `/api/cron/daily-digest`) into **Coolify Scheduled Tasks**, **Dokploy Cron**, or a lightweight **BullMQ / node-cron** worker container with a shared `CRON_SECRET` Bearer header.
- **Next.js Image Optimization (`next/image`):** On Vercel, `next/image` runs on Vercel’s metered transformation edge. Inside Docker on Hetzner, Next.js runs image optimization locally using **`sharp`**—make sure `sharp` is installed in your production image (and fronted by Cloudflare’s CDN cache so each resized WebP/AVIF is computed once and cached at the edge!).
🗄️ Phase 2: Preparing Neon PostgreSQL for Persistent Container Connections
Moving from Vercel Serverless to a persistent Hetzner VPS actually makes PostgreSQL **faster and easier to tune**—because your Next.js Node.js process stays warm in memory instead of cold-booting hundreds of ephemeral Lambda functions. However, you must configure connection strings properly so you never exhaust Neon’s connection limits or trigger idle-timeout disconnects.
1. Create an Isolated Staging Branch in 2 Seconds
Install the **Neon CLI (`neonctl`)** or open the Neon Console and spin up a copy-on-write branch of your production database specifically for Hetzner testing:
neonctl branches create --project-id your-project-id --name staging-hetzner
Because Neon branches use copy-on-write storage, this gives you an instant, zero-cost clone of your production schema and data to hammer with load tests on Hetzner without risking a single production row.
2. Configure Dual Connection Strings (Pooled + Direct)
In your Hetzner environment variables, supply both endpoints from Neon:
- **`DATABASE_URL` (Application Traffic — Pooled):** Use Neon’s **PgBouncer `-pooler` hostname** with `?sslmode=require&pgbouncer=true&connect_timeout=15`. In Prisma or Drizzle/node-postgres (`pg`), cap your per-container pool size explicitly (`connection_limit=10` to `15`) so rolling zero-downtime deployments (where old and new containers overlap briefly) never spike connections.
- **`DIRECT_URL` (Migrations Only — Unpooled):** Use the direct (non-`-pooler`) Neon hostname exclusively for `npx prisma migrate deploy` or `drizzle-kit migrate` during your build/release hook—PgBouncer transaction pooling breaks advisory locks used by migration tools.
- **Keep Scale-to-Zero Smart:** On production paid Neon plans, consider raising **auto-suspend delay** (or disabling scale-to-zero on your primary production compute) so your first morning request never eats a 400 ms Neon cold wake-up! 🗄️
📦 Phase 3: Migrating From Vercel Blob to S3-Compatible Blob Storage
You have two smart paths for Blob storage:
- **Fastest Zero-Risk Path (Two-Stage):** Keep `@vercel/blob` running for Week 1 while you stabilize your Hetzner VPS (Vercel Blob works fine via `BLOB_READ_WRITE_TOKEN` from external servers), *then* migrate storage in Week 2.
- **Clean Full Exit Path (Recommended):** Migrate straight to **Hetzner Object Storage** (€6.49/mo for 1 TB storage + 1 TB egress + free API calls, located in the same Falkenstein/Nuremberg/Helsinki data center!) or **Cloudflare R2** ($0.015/GB storage, **$0 egress fees** worldwide).
1. Replace `@vercel/blob` With a Thin S3 Storage Wrapper
Install the standard AWS S3 v3 SDK (`npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner`) and wrap uploads in a clean `lib/storage.ts` helper so you are never vendor-locked again:
import { S3Client, PutObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
export const s3 = new S3Client({
region: process.env.S3_REGION || "fsn1", // e.g., fsn1 for Hetzner or auto for R2
endpoint: process.env.S3_ENDPOINT!, // e.g., https://fsn1.your-objectstorage.com
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID!,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
},
forcePathStyle: false,
});
export async function createPresignedUploadUrl(key: string, contentType: string) {
const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET_NAME!,
Key: key,
ContentType: contentType,
CacheControl: "public, max-age=31536000, immutable",
});
return getSignedUrl(s3, command, { expiresIn: 300 });
}
export async function deleteBlob(key: string) {
await s3.send(new DeleteObjectCommand({
Bucket: process.env.S3_BUCKET_NAME!,
Key: key,
}));
}
*Senior engineering tip:* Always use **presigned upload URLs** so browsers upload 20 MB images or PDFs directly to S3/R2—keeping heavy multipart upload buffers completely off your Hetzner VPS RAM!
2. Bulk-Copy Existing Blobs & Rewrite Neon URLs Safely
Write a short Node.js migration script (using `@vercel/blob`’s `list()` cursor + streaming `fetch` straight into `PutObjectCommand`—or download locally and blast up with **`rclone copy --transfers=32`**) to mirror every existing blob key verbatim into your new bucket behind a custom CDN domain (e.g., `cdn.yourdomain.com`).
Once every object is verified (`HEAD` check returns 200), update stored URLs inside Neon PostgreSQL in a single atomic transaction (test on your `staging-hetzner` branch first!):
BEGIN;
UPDATE media_assets
SET url = REPLACE(
url,
'https://your-store-id.public.blob.vercel-storage.com/',
'https://cdn.yourdomain.com/'
)
WHERE url LIKE 'https://your-store-id.public.blob.vercel-storage.com/%';
-- Verify row count before committing!
SELECT COUNT(*) FROM media_assets
WHERE url LIKE 'https://your-store-id.public.blob.vercel-storage.com/%';
COMMIT;
Leave your old Vercel Blob store active in read-only mode for **7 days post-cutover** so any cached social-share links or stale browser caches never hit a 404. 📦
🖥️ Phase 4: Provisioning & Hardening Your Hetzner VPS + Installing Coolify
Skip the smallest 2 GB RAM instances if you plan to run Docker builds on the same server—TypeScript type-checking plus `next build` easily spikes past 3.5 GB of RAM. Start with a **Hetzner CX33 (4 vCPU, 8 GB RAM, 80 GB NVMe, ~€8.49/mo)** or **CAX21 (ARM64 4 vCPU, 8 GB RAM, ~€10.49/mo)** running **Ubuntu 24.04 LTS**, and enable **Hetzner Automated Backups**.
🔐 5-Minute Server Hardening Checklist
- **Attach a Hetzner Cloud Firewall** in the Hetzner Console *before* booting: allow **TCP 80** (HTTP), **TCP 443** (HTTPS), and **TCP 22** (SSH—ideally locked to your static IP or **Tailscale** private mesh VPN), blocking all other inbound ports by default.
- **Add a 4 GB Swapfile** (cheap insurance against sudden OOM spikes during simultaneous Docker builds):
fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
sysctl vm.swappiness=10
- **Disable Password SSH & Enable Unattended Security Upgrades:** Ensure `/etc/ssh/sshd_config` sets `PasswordAuthentication no`, `PermitRootLogin prohibit-password`, and run `apt update && apt install -y fail2ban unattended-upgrades`.
🛠️ Choosing Your Self-Hosted PaaS: Coolify vs. Dokploy vs. Kamal 2
| Self-Hosted Tool | Best For | Key Strengths | Resource Overhead |
| --- | --- | --- | --- |
| **Coolify** | Full Vercel-like GUI experience | GitHub webhooks, PR preview deploys, built-in Traefik SSL, scheduled cron tasks, one-click Redis/Uptime Kuma | ~500–800 MB RAM |
| **Dokploy** | Lean Docker/Compose teams | Ultra-snappy Next.js/Traefik dashboard, native Docker Swarm support, fast multi-server deploys | ~300–500 MB RAM |
| **Kamal 2** | CLI-first DevOps purists | Zero dashboard overhead on VPS; deploys via SSH + kamal-proxy straight from GitHub Actions | ~50 MB RAM |
For most teams migrating from Vercel, **Coolify** delivers the closest zero-friction workflow. Install it on your hardened Ubuntu 24.04 box in one line:
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash
Immediately secure the Coolify dashboard behind its own subdomain (e.g., `deploy.yourdomain.com`) with HTTPS enabled, close port `8000` on your Hetzner Firewall, and connect your GitHub repository via GitHub App integration. ⚙️
🐳 Phase 5: The Production-Grade Next.js Multi-Stage Dockerfile
While Coolify’s Nixpacks can auto-build Next.js, writing an explicit **3-stage standalone `Dockerfile**` cuts build times in half, guarantees identical local-to-prod parity, includes `sharp` for `next/image`, runs as a non-root user, and exposes a real `/api/health` check for zero-downtime rolling swaps:
# Stage 1: Install dependencies
FROM node:22-alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json* pnpm-lock.yaml* ./
RUN corepack enable && \
if [ -f pnpm-lock.yaml ]; then pnpm install --frozen-lockfile; \
else npm ci; fi
# Stage 2: Build Next.js standalone bundle
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
# Pass public build-time env vars via Docker build args if required
ARG NEXT_PUBLIC_CDN_URL
ENV NEXT_PUBLIC_CDN_URL=$NEXT_PUBLIC_CDN_URL
RUN npm run build
# Stage 3: Minimal production runtime
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/api/health || exit 1
CMD ["node", "server.js"]
🩺 Build a Real `/api/health` Endpoint
Never return a blind `200 OK` from `/api/health`. Have your health route execute a lightweight `SELECT 1` against Neon PostgreSQL (with a 2-second timeout). That way, Coolify/Traefik will **never** shift live traffic onto a newly built container if a mistyped `DATABASE_URL` or missing secret prevents database connectivity!
🌐 Phase 6: Zero-Downtime DNS Cutover, Cloudflare Edge, and Instant Rollback
Do not point users blindly at Hetzner and pray. Follow this battle-tested **4-step cutover sequence**:
- **T-Minus 24 Hours — Drop DNS TTL to 60 Seconds:** In Cloudflare (or your DNS registrar), lower the TTL on your root `@` and `www` records to **Auto / 60 seconds** so changes propagate globally in under two minutes.
- **T-Minus 4 Hours — Load Test the Staging Subdomain (`next.yourdomain.com`):** Point a staging subdomain at your Hetzner IP connected to your `staging-hetzner` Neon branch, and run a 2-minute **`k6` load test** (`k6 run --vus 50 --duration 2m loadtest.js`). Watch `htop` and Neon’s Connection Monitor to confirm CPU stays under 60%, RAM stays steady with zero memory leaks, and `p95` TTFB sits under **150 ms**.
- **T-Minus 15 Minutes — Switch Env Vars to Production Neon + Production S3:** Update Coolify’s production service to point to your main Neon PostgreSQL branch (`DATABASE_URL` + `DIRECT_URL`), redeploy, and verify `/api/health` returns `200 OK` locally via `curl -H "Host: yourdomain.com" http://<HETZNER_IP>/api/health`.
- **Cutover & Cloudflare Fronting:** Update your `@` and `www` `A` (and `AAAA` IPv6!) records in Cloudflare to your Hetzner VPS IP with **Orange Cloud Proxy ON** (SSL mode set to **Full (Strict)**). Add a Cloudflare Cache Rule to cache `/_next/static/*` aggressively at the edge (1-year TTL)—offloading 70%+ of static JS/CSS hits before they ever touch your Hetzner box!
*The 30-Second Rollback Plan:* Keep your Vercel deployment live and untouched for **72 hours** after cutover. If Sentry alerts spike or an unexpected edge case appears, simply flip the `A` record in Cloudflare back to Vercel’s IP (`76.76.21.21`)—within 60 seconds, 100% of traffic is safely back on Vercel while you debug calmly. 🔄
✅ Final Pre-Cutover DevOps Verification Checklist
Before flipping DNS on launch day, verify every single box on this list:
- **Region Pairing Verified:** Hetzner VPS (`fsn1`/`nbg1` or `ash`) sits in the same geographic corridor (< 8 ms RTT) as your Neon PostgreSQL compute.
- **Dual Neon URLs Set:** Pooled `-pooler` string in `DATABASE_URL` (with capped pool size) and direct unpooled string in `DIRECT_URL` for migrations.
- **Blob Assets Mirrored & Checked:** 100% of existing Vercel Blob files copied to Hetzner Object Storage / Cloudflare R2 with `Cache-Control: public, max-age=31536000, immutable` and verified `200 OK` via `cdn.yourdomain.com`.
- **All Vercel Crons Migrated:** Every `vercel.json` cron job recreated as a Coolify/Dokploy scheduled task with verified secret auth.
- **Firewall & Swap Active:** Only ports 80/443 (plus restricted SSH/Tailscale) open on Hetzner Cloud Firewall; 4 GB swapfile active; automated Hetzner backups enabled.
- **Observability Live:** **Sentry** (error tracking), **Better Stack** or self-hosted **Uptime Kuma** (1-minute external ping on `/api/health`), and **Coolify disk-usage alerts** (> 80% disk triggers Telegram/Slack ping so Docker build caches never fill your NVMe!).
- **Zero-Downtime Healthcheck Passing:** Container starts cleanly as non-root `nextjs`, serves `next/image` via `sharp`, and passes `/api/health` DB checks.
Migrating from Vercel to Hetzner with S3 Blob storage and Neon PostgreSQL gives you the rarest combination in modern web engineering: **startup-speed developer ergonomics, enterprise-grade managed PostgreSQL reliability, and rock-bottom bare-metal economics.** Once your first Git push rolls out smoothly across Traefik with an $8.49 VPS invoice waiting at the end of the month, you will wonder why you didn't make the jump sooner. 🚀🐘✨
#VercelToHetzner #HetznerCloud #NeonPostgreSQL #DevOpsGuide #SelfHosting #Coolify #Dokploy #NextJSDeployment #CloudMigration #BlobStorage #CloudflareR2 #DockerProduction #PostgreSQL #WebInfrastructure #SaaSArchitecture #CostOptimization #FullStackEngineering #ServerlessToVPS #LinuxHardening #ModernDevOps
STAY HERE
🤝 The December Community Exchange: How to Organize a Neighborhood Skill-Sharing Network for Winter Projects, Learning, and Connection
⚖️ Why December 10 Matters: Understanding Human Rights Day and the Universal Principles That Shape Modern Society
🌉 How Bridges Survive Freezing Temperatures: The Hidden Engineering Behind Expansion Joints, Ice Protection, and Winter Maintenance
STAY HERE
🚗 The December Road Trip Handbook: How to Plan Winter Routes, Prepare Your Vehicle, and Explore Seasonal Destinations Safely
🎶 The Winter Vinyl Listening Club: How to Discover Forgotten Albums, Care for Records, and Create Your Own December Music Collection
🧩 The December Mechanical Puzzle Workshop: How to Build Wooden Brain Teasers and Explore the Engineering Behind Them
STAY HERE
🌲 The Winter Evergreen Survival Guide: How Pine, Fir, and Spruce Trees Endure Freezing Temperatures Without Losing Their Needles
🐦 Why Do Birds Puff Up Their Feathers in December? Nature's Ingenious Approach to Thermal Insulation
🍪 The December Spice Encyclopedia: How Cinnamon, Cloves, Cardamom, and Nutmeg Became Associated With Winter Celebrations
STAY HERE
🍫 The Science of Perfect Hot Chocolate: How Temperature, Cocoa Quality, and Ingredients Transform Every Cup
🏛️ December in Ancient Civilizations: How Romans, Vikings, and Other Societies Experienced the Approach of Midwinter
👹 The Night of Krampus: Exploring the Origins, Folklore, and Cultural Significance of December 5