Skip to content

Engineering · DevOps

Next.js · Strapi 5 · Cloudflare: notes from production The self-hosted setup we run, and the cache trap that hid our deploys

We run Next.js and Strapi 5 on a self-managed Linux server: PostgreSQL for data, each app built once and kept alive by pm2 in production mode, nginx in front, Cloudflare at the edge. It keeps cost and data under control, provided HTML caching is set on purpose: Next.js marks prerendered pages cacheable by shared caches for a year.

Written by
Wael ChabchoubiFounder & Tech Lead
Published
Updated
Reading time
11 minLire en français

What does a self-hosted Next.js and Strapi setup look like?

Five layers, each with one job. Cloudflare handles DNS, TLS and the edge. nginx holds the origin certificate and routes each domain to a local port. Next.js renders the site, Strapi serves the API and the admin, and PostgreSQL stores the data. Everything except Cloudflare runs on one Linux server we operate.

This is the shape of the systems we build and run for clients such as TSS Company, whose ERP uses Strapi 5, Next.js 16 and PostgreSQL. Its front end and its API live on two subdomains, each with its own nginx virtual host, and each process listens on 127.0.0.1 only: nginx is the single front door. The site you are reading uses the same edge, proxy and process layers, without Strapi.

Our production stack for Next.js and Strapi, as of October 2026
LayerWhat we useWhyWatch out for
EdgeCloudflare proxy, origin certificate, Full (strict) TLSDNS, TLS and protection in one placeHTML caching rules; Cloudflare can also inject scripts into HTML
Reverse proxynginx, one virtual host per domainRoutes each domain to a local port, sets headersOne add_header in a location drops the server-level headers
Front endNext.js 16 (App Router) with next startServer rendering and prerendered pagesThe Cache-Control of prerendered pages
API and adminStrapi 5 with strapi startContent types, roles, REST API, admin panelIt runs the compiled dist folder, not src
DatabasePostgreSQL, one database and role per appRelational data, exact numeric money columnsPool size on a cluster shared by several apps
Processespm2 in fork mode, memory limit, saved process listRestarts after a crash or a rebootNever serve production from a development server

Nothing here is exotic, and that is the point: every layer is documented, free to run and replaceable. What follows are the details that cost us time in real deployments, so that they do not cost you any.

Why do we self-host instead of using a managed platform?

Because our clients' systems are business software, not global media sites. An ERP or a B2B catalogue serves a known audience, mostly in one country, and gains more from data under control and one predictable bill than from rendering in many regions. We also want to operate what we build, end to end.

Self-hosting is not free of work. Someone has to patch the server, watch memory and disk, renew certificates, test backups and react when a process dies. We do that as part of our DevOps and hosting service. If nobody on your side can own those tasks, and no partner does it for you, a managed platform is the safer choice; the last section says when.

How do we keep Next.js and Strapi running in production?

Each app is built once, then started in production mode under pm2, a Node.js process manager. pm2 restarts a process that crashes or exceeds its memory limit, and its saved process list survives a server reboot. A development server never serves real traffic, not even for a quick fix.

We learned the last rule the hard way. On a shared server, a Next.js development server started by hand for a quick check kept running. It grew to 3.76 GB of memory, the Linux out-of-memory killer stopped it, and because no supervisor knew about it, nothing started it again. In production mode the same front end needs about 70 MB.

Here is the kind of pm2 process file we use for a Next.js front end, simplified:

module.exports = {
  apps: [
    {
      name: 'site-front',
      script: 'node_modules/next/dist/bin/next',
      args: 'start -H 127.0.0.1 -p 3000',   // localhost only: nginx is the front door
      node_args: '--max-old-space-size=384', // heap cap for this app
      max_memory_restart: '600M',            // pm2 restarts it above this
      exec_mode: 'fork',
      autorestart: true,
      env: { NODE_ENV: 'production', NEXT_TELEMETRY_DISABLED: '1' },
    },
  ],
};
js · ecosystem.config.js for one Next.js app. Start with pm2 start ecosystem.config.js, then pm2 save.

Builds need the same discipline. Several Node.js applications share our servers, and an uncapped next build can take enough memory to slow down or stop its neighbours. We always build with a cap, NODE_OPTIONS=--max-old-space-size=1536, and restart only the application concerned, never every process at once.

Strapi adds a trap of its own: strapi start runs the compiled dist/ folder, not your source. After a change in src/, run the build, then restart. A type check alone changes nothing in what is running; we once shipped a start-up fix that stayed inactive for exactly that reason.

Which Strapi 5 behaviours should you know before going live?

Six behaviours of Strapi 5 cost us time in real projects: hooks that cannot see component values, documentId in URLs, drafts the API hides, money rounded to two decimals in PostgreSQL, duplicate CORS headers and negative query limits. Each has a simple fix once you know it, listed below.

  • Lifecycle hooks and components. Strapi 5 saves components, such as the lines of an invoice, before the beforeCreate hook runs, so the hook only sees references, not the line values. We compute document totals in the controller, which receives the raw request body, and run side effects such as stock movements and client balances in afterCreate and afterUpdate.
  • documentId, not id. The REST API addresses entries by documentId. Numeric ids are still accepted when you write a relation, which makes mixed code easy to get wrong. See the Document Service documentation (opens in a new tab).
  • Draft & Publish. On a content type with Draft & Publish (opens in a new tab) enabled, strapi.documents().create() without status: 'published' creates a draft, and the REST API does not return drafts by default. Lists stay empty and nothing looks broken.
  • Money and decimals. On an invoicing application we deployed, decimal fields came out as numeric(10,2) in PostgreSQL, so 14.875 became 14.88. Tunisian dinar amounts have three decimals (millimes). We migrated 52 columns to numeric(14,3); any decimal field added later needs its own migration.
  • CORS between two subdomains. Let Strapi send the CORS headers. If nginx adds Access-Control-Allow-Origin as well, the browser receives two values and rejects the response. It matters for files too: a PDF export that draws uploaded logos in the browser needs those headers on /uploads.
  • Negative limits. strapi.db.query().findMany({ limit: -1 }) fails on PostgreSQL (LIMIT must not be negative). The Document Service tolerates it; with the Query Engine, simply omit the limit.

Why did Cloudflare keep serving old pages after a deploy?

Next.js sends s-maxage=31536000 on prerendered pages, which lets shared caches keep them for a year. On one of our deployments behind Cloudflare, visitors kept receiving old HTML for weeks after new releases, and that HTML pointed to JavaScript files our server had already deleted. The response header said DYNAMIC.

The Next.js documentation (opens in a new tab) is explicit: static pages without revalidation get s-maxage=31536000, one year, and the content-hashed assets under /_next/static/ get public, max-age=31536000, immutable. Cloudflare does not cache HTML by default (opens in a new tab), but its Cache-Control documentation (opens in a new tab) explains that s-maxage governs shared caches and that Free, Pro and Business plans follow the origin header by default. As soon as HTML is cached at the edge, a year-long header becomes a year-long page.

Two details made the problem hard to see. The scripts referenced by the stale HTML returned 404 from our server, yet loaded through Cloudflare, which still had them in its cache. And the HTML response carried cf-cache-status: DYNAMIC, which reads as “not cached”. Do not rely on that header alone.

How to tell, in three commands

Compare what the origin serves with what the public URL returns, then add a cache-busting parameter. If the plain public URL differs from the origin and the parameterised one matches it, a cache sits in between.

# 1. What the origin serves (Cloudflare bypassed)
curl -s http://127.0.0.1:3007/ -H "Host: www.example.com" \
  | grep -o '/_next/static/chunks/[^"]*' | sort -u | head -3

# 2. What visitors receive
curl -s https://www.example.com/ \
  | grep -o '/_next/static/chunks/[^"]*' | sort -u | head -3

# 3. The same page with a cache-busting parameter
curl -s "https://www.example.com/?v=$(date +%s)" \
  | grep -o '/_next/static/chunks/[^"]*' | sort -u | head -3
bash · Different chunk names in 1 and 2, identical in 1 and 3: the HTML is cached between the origin and the visitor.

How did we fix it for good?

We made HTML revalidate on every request, kept hashed assets immutable, versioned assets with a deployment id and purged Cloudflare once. The header fix stops new stale copies; only the purge removes the copies already stored. On this site, every page now sends public, max-age=0, must-revalidate, and nginx enforces it too.

  1. HTML must revalidate. On the affected application we override the header in nginx: proxy_hide_header Cache-Control, then add_header Cache-Control "private, no-cache, no-store, must-revalidate" on location /. This site sets public, max-age=0, must-revalidate in next.config.ts.
  2. Hashed assets stay immutable. /_next/static/ keeps public, max-age=31536000, immutable: those file names change with every build, so a long cache is safe.
  3. Version the build. We set `deploymentId` (opens in a new tab) from NEXT_DEPLOYMENT_ID, filled with the commit hash at build time. Next.js appends ?dpl= to static asset URLs and uses the id to detect version skew (opens in a new tab) between an open tab and a new deployment.
  4. Purge once. New headers and a new build do not evict what Cloudflare already holds. Purge after the fix, then check again with a cache-busting parameter.
// next.config.ts (excerpt)
const revalidate = [{ key: 'Cache-Control', value: 'public, max-age=0, must-revalidate' }];

const nextConfig = {
  deploymentId: process.env.NEXT_DEPLOYMENT_ID || undefined, // commit hash, set at build time
  async headers() {
    return [
      { source: '/:locale(en|fr)', headers: revalidate },
      { source: '/:locale(en|fr)/:path*', headers: revalidate },
    ];
  },
};
ts · The cache headers of ait-tun.com, as shipped.

The nginx detail that removed our security headers

Fixing the cache exposed a second trap. In nginx, as soon as a location block contains one add_header, it stops inheriting every add_header of the server block. A location added only to set Cache-Control silently loses HSTS, X-Content-Type-Options, Referrer-Policy and the content security policy. The always flag does not change that; it only concerns response codes. The nginx documentation (opens in a new tab) states the rule, and recent versions (1.29.3 and later) add an add_header_inherit directive. We keep security headers in one file and include it in every location.

location / {
    proxy_pass http://127.0.0.1:3007;
    proxy_hide_header Cache-Control;
    include snippets/security-headers.conf;   # re-declared: add_header is not inherited here
    add_header Cache-Control "private, no-cache, no-store, must-revalidate" always;
}
nginx · Simplified virtual host: HTML revalidates and the security headers are declared again.

What does a deploy look like, step by step?

Five steps, always in the same order: build with a memory cap and the commit hash as deployment id, restart only the process concerned, check the origin directly, check the public URL with a cache-busting parameter, and purge Cloudflare when HTML could have been cached before. Skipping the last check is how stale pages survive.

  1. NEXT_DEPLOYMENT_ID=$(git rev-parse --short HEAD) NODE_OPTIONS=--max-old-space-size=1536 npx next build for the front end, npm run build for Strapi.
  2. pm2 restart <app> for that application only, never pm2 restart all on a shared server.
  3. curl -sI http://127.0.0.1:<port>/ to confirm that the origin answers with the expected Cache-Control.
  4. curl -sI "https://<domain>/?v=$RANDOM" to confirm what the edge returns now.
  5. A Cloudflare purge if an older configuration could have cached HTML.

Did Next.js 16 bring any surprise?

One, on this very site. With next start bound to 127.0.0.1, Next.js 16.4 built the proxy request URL with localhost but compared rewrites against 127.0.0.1, so every localised French URL redirected to itself. Setting skipProxyUrlNormalize to true in next.config.ts ended the loop, and French pages load normally.

The loop only appeared with the production server bound to 127.0.0.1, which is how we run every app behind nginx. The broader lesson: test the production build with the same host binding and proxy as the live server before switching DNS.

What should be on your go-live checklist?

Check processes, caching, headers, data and recovery before the first visitor: supervised production processes, revalidating HTML, immutable hashed assets, security headers in every location, money columns with the right precision, a tested restore, and a purge after the switch. Each line below follows from an incident described above.

  • Front end and API run under pm2 or systemd in production mode, with a memory limit and a saved process list.
  • No development server on the production machine: no next dev, no strapi develop.
  • HTML responses send a revalidating Cache-Control; /_next/static/ stays immutable.
  • deploymentId is set from the commit hash.
  • Security headers are declared again in every nginx location that adds a header.
  • CORS headers come from one layer only.
  • Money columns are checked in PostgreSQL (numeric with the right scale), not only in the Strapi schema.
  • Builds are capped with NODE_OPTIONS=--max-old-space-size on shared servers.
  • Backups are scheduled and one restore has actually been tested.
  • Cloudflare is purged after the switch, then checked with a cache-busting URL.

When is this setup the wrong choice?

When nobody will own the server. Self-hosting trades a platform bill for operational work: updates, monitoring, backups and incidents. It is also the wrong tool if you need rendering in many regions, automatic scaling for traffic spikes or CDN purges wired to every content change. Then a managed platform earns its price.

For most of the business software we build, an ERP, a CRM, a catalogue or a SaaS for a known market, those needs do not apply, and one well-run server is simpler to reason about. Our Next.js and Strapi pages explain where each fits, and the web applications and SaaS service shows how we scope a project. The vocabulary is in the glossary.

FAQ

Questions readers ask

Is Strapi 5 ready for production business applications?

Yes, with care. We run Strapi 5 in production behind Next.js for ERP and content workloads. Plan for its specifics: totals computed in controllers, documentId in URLs, Draft & Publish visibility, decimal precision in PostgreSQL, and a build before every restart. Most problems we met came from these details, not from Strapi itself.

Should Cloudflare cache Next.js pages?

Only deliberately. The hashed files under /_next/static/ can be cached for a year. HTML should revalidate, unless you also purge the cache after every deploy and every content change. Next.js marks prerendered pages with s-maxage=31536000, so any rule that caches HTML at the edge can keep a page for a year.

Can Next.js and Strapi run on the same server?

Yes. We run both on one Linux server, each as its own pm2 process listening on localhost, behind nginx with one virtual host per domain. Give each process its own memory limit, cap the memory of builds, and size the PostgreSQL connection pool to what a shared cluster can afford.

Sources

Sources and references

External facts in this guide come from these documents. Examples from our projects are first-hand.

  1. Using a CDN with Next.js (CDN caching guide) (opens in a new tab)Next.js documentation
  2. deploymentId (next.config.js) (opens in a new tab)Next.js documentation
  3. Self-hosting, including version skew (opens in a new tab)Next.js documentation
  4. Default cache behavior (opens in a new tab)Cloudflare documentation
  5. Cache-Control and Origin Cache Control (opens in a new tab)Cloudflare documentation
  6. Module ngx_http_headers_module: add_header (opens in a new tab)nginx documentation
  7. Document Service API (opens in a new tab)Strapi documentation
  8. Draft & Publish (opens in a new tab)Strapi documentation

Want this setup run for you?

We build on Next.js and Strapi, deploy on servers we operate, and keep them running after launch.