Skip to content
Back to blog

Blog

Self-Hosting Next.js on Coolify Behind Cloudflare: The Production Architecture Guide

8 min
Table of Contents
Diagram showing a request travelling from a visitor through Cloudflare, a Tunnel and Traefik to a Next.js container.

Most tutorials on self-hosting Next.js end the moment next start responds on port 3000. You get a container running on a Linux server, point a DNS record at it, and call it a day.

Then real traffic arrives. Visitors far from your server wait 600ms for a document that could have been served from an edge node in 30ms. You enable Cloudflare proxy caching, and suddenly your admin routes or auth cookies leak across sessions, or Cloudflare refuses to cache anything at all because of a silent Set-Cookie header. Your next/image endpoint hammers your origin CPU, and a fresh deploy serves stale HTML for hours.

I run this exact site on Next.js 16 inside Coolify on a single Linux server, fronted by Cloudflare. There is no Vercel edge network, no managed ISR CDN, and no x-vercel-* headers anywhere in production. Yet the site still feels instant globally because Cloudflare handles the edge caching while Coolify handles builds, TLS, and container orchestration.

This is the complete production setup, including the cache rules, header traps, and deployment trade-offs nobody puts in the quickstart docs.


Why self-host Next.js on Coolify instead of a managed PaaS

Managed platforms are great until your bandwidth, seat count, or side-project footprint outgrows the free tier. Moving to Coolify gives you the same git push deployment loop, preview environments, and automatic container rollouts on hardware you control.

Whether you run on a modest self-hosted box, a dedicated machine, or an entry-level virtual server, a typical Linux host gives you dedicated CPU cores, plenty of RAM, and unmetered compute at a fraction of cloud platform markups. That provides more than enough headroom to build a Next.js App Router bundle, run a PostgreSQL database, and keep a handful of other self-hosted services alive on the same box.

The catch is geography. A single Linux server in one region is fast for nearby visitors and noticeably slower for everyone else. Without a CDN caching HTML and optimised images at the edge, every page view travels all the way back to your origin container.


The production request flow

When you self-host Next.js behind Cloudflare, every request passes through four layers:

text
Visitor
  -> Cloudflare Edge (DNS, TLS, Cache Rules, WAF)
    -> Cloudflare Tunnel or Origin Firewall
      -> Coolify (Traefik Reverse Proxy)
        -> Next.js Container (`next start` on port 3000)

Notice what is missing. On Vercel, the platform sits inside the build and runtime lifecycle, automatically invalidating CDN cache tags when revalidate fires. On a self-hosted Node server, Next.js only manages its own in-memory/filesystem Data Cache and Full Route Cache inside the container. Cloudflare has no idea when Next.js revalidates a page unless you design the headers and cache rules intentionally.

That gap is where almost every self-hosted Next.js deployment breaks.


Step 1: Build Next.js cleanly inside Coolify

You do not need a complicated custom Dockerfile for most Next.js apps, though using output: 'standalone' in next.config.js is worth it if you want smaller container images and faster rollbacks.

In your Next.js configuration, make sure two things are explicit:

  1. Image remote patterns and cache TTL. Next.js optimises images on the fly via /_next/image. By default, the minimum cache TTL is short, which forces your server to re-process images more often than necessary. Setting minimumCacheTTL to 7 days (604800 seconds) keeps CPU usage flat.
  2. Trusting the proxy. Coolify routes traffic through Traefik, and Cloudflare sits in front of Traefik. If your app reads client IPs or hostnames for redirects, read cf-connecting-ip and cf-ipcountry rather than assuming a direct socket connection.

If you run Coolify on ARM64 hardware, pin your Coolify image to a stable release tag rather than a nightly or next-aarch64 tag. I learned this the hard way after a routine update broke container startup, which I documented in Fix Coolify ARM S6_INITIALIZED Not Set Error.

Connecting Coolify to Cloudflare safely

You have two solid options for wiring Cloudflare to your Coolify origin:

  • Cloudflare Proxy + Origin Firewall: Point your A/AAAA record to your server IP with the orange cloud enabled, set SSL/TLS mode to Full (strict), and lock port 80 and 443 down so only Cloudflare’s published IP ranges can reach your server.
  • Cloudflare Tunnel (cloudflared): Run cloudflared on the server and route traffic directly into Coolify’s Traefik network with zero open inbound ports.

I prefer Cloudflare Tunnel for single-server setups. Your origin IP stays hidden, you never worry about firewall rules drifting, and Coolify still handles internal routing cleanly.


Step 2: Designing Cloudflare Cache Rules that do not break your app

By default, Cloudflare does not cache HTML. It caches static assets like .js, .css, and .png, while passing every HTML document straight to your Next.js server. That is safe, because caching dynamic HTML blindly is dangerous, but it leaves 80% of your potential speed on the table.

To fix this, configure Cloudflare Cache Rules in strict priority order.

PriorityRule NameMatch ConditionAction
1Bypass dynamic & auth routesPath starts with /admin, /api, /authBypass cache
2Cache public HTML pagesExact static paths + /blog, /guides prefixesEligible for cache (Edge TTL + Browser TTL)
3Cache R2 media CDNHostname equals cdn.yourdomain.comEligible for cache
4Cache Next image optimiserPath starts with /_next/imageEligible for cache

Here is what the expression for Rule 2 looks like in practice:

text
(http.host eq "xahidex.com" and starts_with(http.request.uri.path, "/blog"))
or (http.host eq "xahidex.com" and starts_with(http.request.uri.path, "/guides"))
or (http.host eq "xahidex.com" and http.request.uri.path eq "/")
or (http.host eq "xahidex.com" and http.request.uri.path eq "/about")
or (http.host eq "xahidex.com" and http.request.uri.path eq "/dashboard")

Why list paths explicitly instead of caching /* and excluding /api? Because allow-listing is fail-safe. When you add a new OAuth callback, webhook, or authenticated dashboard route next month, it stays uncached by default until you deliberately decide where it belongs.

Edge TTL vs. Browser TTL

Set a different TTL for the edge and the browser. For public HTML pages, I use a longer Edge TTL (for example, 4 to 24 hours, which you can purge on deploy) and a short or zero Browser TTL (Respect Origin or a few minutes).

If you set a 7-day Browser TTL on HTML, returning visitors will stay stuck on an old version of a blog post even after you purge Cloudflare’s edge cache. Keep HTML fresh in the browser and fast at the edge. If you want a deeper refresher on how max-age and stale-while-revalidate interact, read Browser Caching Basics for Faster Websites.


Step 3: The three caching traps that catch Next.js developers

Getting Cache Rules active is half the job. The other half is making sure Next.js and Cloudflare actually agree on what is cacheable.

This is the most common reason people see cf-cache-status: DYNAMIC or BYPASS on pages they explicitly told Cloudflare to cache.

According to Cloudflare’s cache behaviour rules, Cloudflare will not cache a response that includes a Set-Cookie header, because caching a cookie at the edge would serve one visitor’s session or preference cookie to everyone else.

In Next.js, this sneaks in through two places:

  1. Proxy / Middleware (src/proxy.ts in Next.js 16, or middleware.ts in older versions): If your middleware sets a geo cookie, theme cookie, or A/B test cookie on every page request, every HTML response becomes uncacheable.
  2. Server Components reading cookies() or headers(): Calling cookies(), headers(), or an uncached fetch() inside a page opts that route into dynamic rendering, telling Next.js to emit Cache-Control: private, no-cache, no-store.

Keep public, cached routes completely free of server-side per-user state. If you need visitor-specific behaviour like a GDPR banner or country-specific notice, read cf-ipcountry in a lightweight client-side check or an uncached /api call, never in the SSR HTML response of a cached page.

Trap 2: Mixing static pages with live data

Suppose your site has a /dashboard page that shows both slow-changing stats (books read, recent posts) and real-time data (what you are listening to right now).

If you fetch the real-time music API inside the Server Component with cache: 'no-store', Next.js marks /dashboard as dynamic (ƒ /dashboard in next build), which prevents prerendering and slows down every load.

The clean pattern is static seed + client hydration:

  1. Prerender the page shell with export const revalidate = 60 so next build marks it as static/ISR (○ or ◐). Seed the live widgets with cached data.
  2. Bypass /api/* in Cloudflare Cache Rule 1.
  3. Have a small client provider fetch /api/activity (marked no-store) on mount and poll on an interval.

Your HTML loads in under 50ms from a Cloudflare edge POP anywhere in the world, and the live widget updates smoothly a moment later in the browser.

Trap 3: next/image hammering your server

Every time a browser requests /_next/image?url=...&w=1080&q=75, your Coolify container has to fetch the source image, resize it with sharp, and stream it back.

Adding Cache Rule 4 for /_next/image tells Cloudflare to cache each resized variant at the edge. After the first visitor in a region requests a specific width, your Linux server never touches that image transform again. Pair that with Cloudflare R2 for your static media and hero images, and your origin stays nearly idle even during traffic spikes.


Step 4: Purging Cloudflare cache automatically on deploy

Once Cloudflare caches your HTML, pushing a typo fix or a new blog post to Coolify updates your origin container, not Cloudflare’s edge nodes. Until the Edge TTL expires or you purge the cache, visitors keep seeing the cached version.

Coolify makes this straightforward to automate using a post-deployment hook or a GitHub Action step after your build finishes. Create a scoped Cloudflare API Token with Zone -> Cache Purge -> Purge permissions, and trigger a purge request:

bash
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/purge_cache" \
  -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
  -H "Content-Type: application/json" \
  --data '{"purge_everything":true}'

For larger sites where purging everything on every deploy hurts your cache hit ratio, pass a files array with the specific URLs that changed (for example, your homepage, /blog, /feed.xml, and the new post slug) instead of purge_everything.


Step 5: Security headers, CSP, and observability

Running behind Cloudflare does not replace application-level security headers. Set Strict-Transport-Security, X-Content-Type-Options: nosniff, Referrer-Policy, and a Content-Security-Policy directly in next.config.js headers() so they are attached at the origin regardless of how a request reaches your container.

For non-hashed static files in /media/*, avoid immutable. Use something like:

text
Cache-Control: public, max-age=2592000, stale-while-revalidate=86400

That gives you a 30-day browser cache while still allowing replaced assets to refresh gracefully. By contrast, /_next/static/* is content-hashed by Next.js, so it is safe to cache indefinitely.

For analytics without bloating your bundle or sacrificing privacy, you can pair this setup with Cloudflare Web Analytics or a self-hosted instance of Umami on the same Coolify server. And if you are curious what else runs alongside Next.js on my server, I broke down the full container stack in The Best Self-Hosted Open Source Apps I Actually Use and how I back it all up in How I Back Up 20+ Docker Services to Dropbox Automatically.


How to verify your caching actually works

Never assume Cloudflare is caching a route just because you saved a rule. Open a terminal and inspect the response headers directly:

bash
curl -I https://xahidex.com/blog

Look for these three headers in the output:

  • cf-cache-status: HIT (on the second request; MISS on the first is normal)
  • cache-control matching what you expect for that route
  • No set-cookie header on any public HTML response

Then test an API route:

bash
curl -I https://xahidex.com/api/health

You should see cf-cache-status: BYPASS or DYNAMIC.


Should you move off Vercel to Coolify + Cloudflare?

Follow the Next.js Self-Hosting documentation and Next.js Caching guide closely if you decide to make the switch, because you are taking ownership of the edge layer yourself.

If your team needs zero-config per-preview edge deployments, global serverless functions, and instant tag-based ISR invalidation out of the box, stay on a managed platform. Your engineering hours are worth more than a $20 server bill.

If you are building a content-heavy site, a SaaS product with predictable traffic, or a personal platform where you want full control over your infrastructure, databases, and costs, Next.js on Coolify behind Cloudflare is hard to beat. You get near-edge performance globally, predictable $0 to $10/month hosting, and zero vendor lock-in.