Skip to content

Deployment ​

Introduction ​

A Plinth application is an ordinary Node.js process: it listens on a port, answers HTTP requests, and needs a handful of environment variables and writable directories. There is no special hosting requirement. This page covers what the generated application gives you for production: the build step, the settings that must change, how the server shuts down, the health route, running behind a proxy, and the optional persistent server.

Everything here describes the code the scaffolder generates. If you wrote your own entry point, apply the same ideas to it.

Building the application ​

The generated package.json has a build script that bundles the HTTP entry point with tsup:

bash
npm run build

This writes a single ES module, dist/index.js, targeting ES2022. Your own code (controllers, providers, config) is bundled into that file, while the @plinthjs packages and your other dependencies stay external, so node_modules must be present where you run it.

The bundle covers only src/server.ts. The console (plinth), the migrations, and the seeders are not part of it. Those still run through tsx.

Starting the server ​

You have two choices for starting the app in production.

Run the built bundle with Node. This is the lean option and needs no TypeScript tooling at runtime:

bash
node dist/index.js

Or run the TypeScript entry directly with the start script:

bash
npm start

WARNING

npm start runs tsx src/server.ts. The generated package.json lists tsx under dependencies, so a production-only install (npm install --omit=dev) can still run npm start. node dist/index.js needs no TypeScript tooling at all.

Start the process from the project root. The entry point reads .env, src/resources/views, and storage/ relative to the current working directory, so a service manager must set that directory.

The server listens on the port in the PORT environment variable, or 3000 when it is not set:

bash
PORT=8080 node dist/index.js

Running migrations ​

Run migrations as part of your deploy, before the new version starts taking traffic:

bash
npx plinth migrate

This needs tsx (a regular dependency of the generated app) and your source files, plus @plinthjs/cli (a dev dependency), so run it in a build or release step that has your dev dependencies.

Production settings ​

Set these before you go live. Put them in your hosting platform's environment configuration, or in a .env file on the server. Real environment variables take precedence over .env.

bash
APP_ENV=production
APP_DEBUG=false
APP_KEY=base64:...
APP_URL=https://blog.example.com
SESSION_SECURE_COOKIE=true
LOG_LEVEL=warning

APP_ENV and APP_DEBUG ​

APP_ENV=production is the default when the variable is missing. In production the generated app sends the Strict-Transport-Security header, stops logging to the console, and caches compiled views for the life of the process (in other environments views are re-read on each request, so edits show up immediately).

APP_DEBUG=false makes the exception handler show a generic "Internal Server Error" instead of the real error message. Never run with APP_DEBUG=true on a public server, because error pages and JSON errors would expose internals.

APP_KEY ​

The application key is a 32-byte secret used by the encryption services, written as base64: followed by the key. The scaffolder generates one into .env when it creates the project. That value belongs to your development machine, so generate a separate key for each environment and never commit it:

bash
npx plinth key:generate

This command rewrites the APP_KEY line of the local .env file. On a platform that sets variables for you, generate a key once and store it as a secret.

The app fails closed: when APP_ENV is production and APP_KEY is empty, startup stops with this error:

APP_KEY is not set. Run `npx plinth key:generate` (or set APP_KEY in .env) before serving in production.

Changing the key invalidates anything encrypted with the old one. To rotate keys without breaking existing data, put the retired keys in APP_PREVIOUS_KEYS as a comma-separated list, which the config exposes as app.previousKeys, and build your Encrypter with them. See Encryption.

Secure cookies ​

The session cookie is only marked Secure when the session.secure setting is true, which comes from SESSION_SECURE_COOKIE and defaults to false. Set it to true once you serve the site over HTTPS so browsers never send the session cookie over plain HTTP. See Sessions.

The database ​

The default SQLite file lives in storage/database.sqlite, which suits a single server with a persistent disk. For anything larger, switch to MySQL or MariaDB with the DB_* variables described in Installation.

Graceful shutdown ​

Process managers and orchestrators stop a service by sending SIGTERM. The generated entry point handles it with gracefulShutdown:

ts
import { gracefulShutdown, serve } from '@plinthjs/http'

const server = await serve(kernel, port)
gracefulShutdown(server, { onShutdown: closeDatabase })

When SIGTERM or SIGINT arrives, the server stops accepting new connections and lets requests that are already running finish. Then it runs your onShutdown callback (the generated one closes the database connection) and exits with code 0. If the in-flight requests do not finish within the timeout, it runs onShutdown anyway and exits with code 1.

You can tune the behaviour with options:

ts
gracefulShutdown(server, {
  signals: ['SIGTERM', 'SIGINT'], // the default
  timeout: 30_000, // milliseconds to wait for in-flight requests; default 10000
  onShutdown: async () => {
    await closeDatabase()
    await flushQueues()
  },
})

Set your orchestrator's termination grace period to be longer than timeout, so the process can finish before it is killed. gracefulShutdown returns a function that removes the signal handlers, which is useful in tests:

ts
const stop = gracefulShutdown(server, { exit: (code) => recordExit(code) })
stop()

The health route ​

Every generated stack defines GET /up. In the web stacks it returns the HTML OK, and in the API stack it returns JSON:

ts
// web stacks
router.get('/up', (): Response => Response.html('OK')).name('up')

// api stack
router.get('/up', (): Response => Response.json({ status: 'ok' })).name('up')

Point your load balancer or orchestrator probe at it:

bash
curl -i http://localhost:3000/up

The route only proves the process is accepting requests. It does not check the database or any other service. If you want a deeper readiness check, add a route that runs a cheap query and returns a 503 on failure.

Running behind a proxy ​

In production you normally put a reverse proxy (nginx, Caddy, a cloud load balancer) in front of the Node process to terminate TLS. Plinth listens on plain HTTP, so it learns the original scheme and client address from headers the proxy sets. Plinth only believes those headers when the direct peer is a proxy you declared:

  • request.ip() is the socket's remote address by default. From a trusted proxy it is read from X-Forwarded-For (then X-Real-IP).
  • request.isSecure() and the scheme in request.fullUrl() follow X-Forwarded-Proto, and the host in fullUrl() follows X-Forwarded-Host, again only from a trusted proxy.

Declare the proxies with the trustedProxies option of serve() / createServer(): true (every peer, only safe when the Node port is reachable solely through your proxy), a list of exact proxy IP addresses (IPv4-mapped ::ffff: prefixes are normalized), or a predicate that receives the socket address. With a list or predicate, X-Forwarded-For is read from the right, skipping trusted hops, so an address the client put at the front of the header is never believed.

ts
await serve(kernel, port, undefined, { trustedProxies: ['127.0.0.1', '10.0.0.2'] })

The generated entry point reads this from the TRUSTED_PROXIES environment variable: a comma separated list of IPs, or * to trust every peer. It is empty by default, so a freshly generated app ignores forwarding headers. Set it to your proxy's address in production, otherwise request.ip() is the proxy's address and every visitor shares one login throttle bucket.

WARNING

Keep the Node port reachable only from the proxy when you use *, and make the proxy overwrite X-Forwarded-For and X-Forwarded-Proto instead of appending to what the client sent. The login throttle in the generated app keys on request.ip().

A minimal nginx location that does this:

nginx
location / {
  proxy_pass http://127.0.0.1:3000;
  proxy_set_header Host $host;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header X-Forwarded-Proto $scheme;
}

Because the generated entry point does not pass a host to serve, it listens on all interfaces. To bind to the loopback interface only, pass a host as the third argument: serve(kernel, port, '127.0.0.1').

The server also limits request bodies to 1 MiB by default and answers 413 Payload Too Large above that. If you accept uploads, raise the limit:

ts
const server = await serve(kernel, port, undefined, { maxBodyBytes: 10 * 1024 * 1024 })

Serving static files ​

The HTTP kernel only routes requests. It does not serve files from public/. Serve static assets such as robots.txt and compiled frontend files from your reverse proxy or a CDN. The Vue and React stacks include a fallback route that serves the Vite build from public/build, which is fine to start with, but a proxy is faster.

Remember to run npm run frontend:build for the Vue and React stacks so public/build and its manifest exist before the server starts.

The persistent server ​

By default each process runs the application you booted at startup and handles requests through the HttpKernel. The @plinthjs/cluster package adds a persistent server on top of that: it boots your Application once per worker, keeps it warm, resets per-request container state after every request, and can fork several worker processes with node:cluster.

bash
pnpm add @plinthjs/cluster

You replace serve in src/server.ts with an ClusterWorker and an ClusterServer. The worker takes a factory that returns the booted application and its kernel:

ts
import { ClusterServer, ClusterWorker } from '@plinthjs/cluster'
import { HttpKernel, Router } from '@plinthjs/http'

import { createApplication, ensureAppKey } from '../src/bootstrap/app.js'
import { registerWebRoutes } from '../src/routes/web.js'

const worker = new ClusterWorker({
  factory: async () => {
    const app = await createApplication()
    ensureAppKey(app)
    const router = new Router()
    registerWebRoutes(router)
    const kernel = new HttpKernel(router, { container: app })
    return { app, kernel }
  },
})

const server = new ClusterServer(worker)
await server.start({ port: 3000, workers: 4 })

process.on('SIGTERM', () => {
  void server.stop().then(() => process.exit(0))
})

With workers greater than 1, the primary process forks that many workers, re-forks any that exit, and each worker boots its own copy of the application. With the default of one worker, the server runs in-process.

After each request the worker calls forgetScopedInstances() on the container, so any binding you registered with scoped() is rebuilt for the next request. Register request-specific services as scoped bindings, not singletons, or they will leak between requests. See The Service Container and The Persistent Server for hooks such as onBoot, onRequest, and onTick.

WARNING

The persistent server does not install the signal handlers that gracefulShutdown provides, so add your own as shown above. Also, concurrent requests in one worker share the same container, so keep per-request data in Context or on the request object rather than in a scoped service.

Deployment checklist ​

  • Build with npm run build and start with node dist/index.js, from the project root.
  • Set APP_ENV=production, APP_DEBUG=false, a unique APP_KEY, APP_URL, and SESSION_SECURE_COOKIE=true.
  • Run npx plinth migrate before starting the new version.
  • Make storage/ writable and persistent, or move sessions, cache, and logs to shared services.
  • Put a proxy in front that overwrites the X-Forwarded-* headers, set TRUSTED_PROXIES to its address, and probe GET /up.
  • Give the process enough time to drain on SIGTERM.

Released under the MIT License.