Invoicing · Tunisia
E-invoicing in Tunisia: 2026 rules for software
Tunisian e-invoicing from the official texts: who must comply since the 2026 Finance Law, TTN's role, penalties, and what your invoicing software must handle.
Engineering · DevOps
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.
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.
| Layer | What we use | Why | Watch out for |
|---|---|---|---|
| Edge | Cloudflare proxy, origin certificate, Full (strict) TLS | DNS, TLS and protection in one place | HTML caching rules; Cloudflare can also inject scripts into HTML |
| Reverse proxy | nginx, one virtual host per domain | Routes each domain to a local port, sets headers | One add_header in a location drops the server-level headers |
| Front end | Next.js 16 (App Router) with next start | Server rendering and prerendered pages | The Cache-Control of prerendered pages |
| API and admin | Strapi 5 with strapi start | Content types, roles, REST API, admin panel | It runs the compiled dist folder, not src |
| Database | PostgreSQL, one database and role per app | Relational data, exact numeric money columns | Pool size on a cluster shared by several apps |
| Processes | pm2 in fork mode, memory limit, saved process list | Restarts after a crash or a reboot | Never 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.
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.
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' },
},
],
};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.
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.
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. 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).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.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.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.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.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.
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 -3We 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.
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./_next/static/ keeps public, max-age=31536000, immutable: those file names change with every build, so a long cache is safe.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.// 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 },
];
},
};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;
}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.
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.pm2 restart <app> for that application only, never pm2 restart all on a shared server.curl -sI http://127.0.0.1:<port>/ to confirm that the origin answers with the expected Cache-Control.curl -sI "https://<domain>/?v=$RANDOM" to confirm what the edge returns now.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.
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.
next dev, no strapi develop.Cache-Control; /_next/static/ stays immutable.deploymentId is set from the commit hash.location that adds a header.numeric with the right scale), not only in the Strapi schema.NODE_OPTIONS=--max-old-space-size on shared servers.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.
Where this applies
FAQ
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.
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.
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
External facts in this guide come from these documents. Examples from our projects are first-hand.
Keep reading
Invoicing · Tunisia
Tunisian e-invoicing from the official texts: who must comply since the 2026 Finance Law, TTN's role, penalties, and what your invoicing software must handle.
ERP · Decision guide
Custom ERP or Odoo? An honest decision grid for SMEs: process fit, recurring costs, Tunisian tax rules, code ownership, and when Odoo is the better choice.
Agencies · Delivery models
White-label development for agencies: what the agreement covers, who owns code and accounts, how a studio stays invisible, a sample week and a handover list.
We build on Next.js and Strapi, deploy on servers we operate, and keep them running after launch.