New to Rust? Grab our free Rust for Beginners eBook Get it free →
Express Complete Tutorial: Part 5 Deployment Checks

A finished Express app still needs checks before it starts receiving traffic. Express deployment checks test how the app handles requests and whether its deployment assumptions are set for the environment where it will run.
This article walks through checking the request path and reviewing readiness and shutdown behavior.
TL;DR
Before deployment, verify that errors reach a final handler, sessions survive across app instances, static files resolve from a stable root, and the process reports readiness and shuts down cleanly.
- Use Express 5 promise forwarding and four-argument error middleware.
- Use a production session store and configure cookies for HTTPS and the actual proxy.
- Exercise the health endpoint, then verify logs, memory and restart behavior after deployment.
This review treats readiness as observable behavior rather than a configuration checklist. A route is ready when its normal result, missing-resource result, and failure result are deliberate, while deployment readiness also depends on how the process receives traffic and handles termination.
What does Express readiness mean?
An Express app is ready when it handles expected requests, reports failures safely, and can be monitored and restarted by its runtime.
Route handlers receive (req, res, next), while error middleware receives (err, req, res, next).
A request passes through a sequence of middleware and routes until a handler sends a response or passes control onward. Readiness checks ask whether that sequence behaves correctly under expected inputs, missing resources, and failures. They also check deployment assumptions that live outside a route, such as TLS termination, session persistence and the process manager’s restart behavior.
Keep the checks separated by responsibility. Express owns routing and middleware flow, the session store owns persisted session data, the proxy owns forwarded connection details, and the process manager owns restarts. When a test fails, this separation helps identify which layer needs attention instead of changing unrelated middleware.
A useful baseline is a small test matrix: a normal request, an unknown path, invalid input, a failed dependency and a request made through the deployed HTTPS endpoint. Record the expected status and whether the response body can safely be shown to a client. Do not use a successful home-page response as proof that every dependency or protected route is ready.
How to check an Express app before deployment
Use a test environment to exercise each route and middleware branch before releasing.
Step 1: Confirm routes and asynchronous errors
Express 5 forwards returned rejected Promises, while callback APIs pass errors to next(err).
app.get('/users/:id', async (req, res) => {
const user = await findUser(req.params.id);
if (!user) return res.sendStatus(404);
res.json(user);
});
app.get('/legacy', (req, res, next) => {
readLegacyData((err, data) => {
if (err) return next(err);
res.json(data);
});
});
Test a known user, an unknown identifier and a simulated rejected lookup. Confirm the responses and error path in the test environment.
Step 2: Add the final error handler
Mount the final error handler after routes and ordinary middleware. Return a generic response, log diagnostic details on the server, and delegate when headers have already been sent.
app.use((err, req, res, next) => {
console.error(err);
if (res.headersSent) return next(err);
res.status(err.statusCode || 500).json({ error: 'Request failed' });
});
Step 3: Verify sessions behind HTTPS
The default express-session store keeps data in memory and suits local testing. Configure a supported shared store for production, especially when requests can reach different instances.
app.set('trust proxy', 1); // only when one trusted proxy sits in front
app.use(session({
name: 'sessionId',
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true, sameSite: 'lax' },
store: productionSessionStore
}));
productionSessionStore represents the session-store adapter configured by the application. Use the adapter installed and tested for the deployment.
Keep the session secret out of source control and set proxy trust to match the trusted proxy count.
Test login, a protected request, logout, and cookie behavior through the deployed HTTPS host. If the cookie is missing, check TLS termination, proxy trust, cookie flags, domain and browser policy before blaming route logic.
Step 4: Resolve static assets from the app directory
A relative static root can resolve from a different working directory when the service starts under a supervisor. Build the path from the module location so deployment does not depend on the shell’s current directory.
const path = require('node:path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Request a known asset through the public URL and confirm a successful response with the expected content type. A 404 often means the mount prefix and URL differ, the file is absent from the deployed artifact, or the root points at the wrong directory. Express documents static serving at its static-files guide.
Step 5: Review security and proxy assumptions
Serve sensitive traffic over TLS, validate user input, keep dependencies reviewed, and set security headers with Helmet. Disable the X-Powered-By header to reduce casual fingerprinting, while recognizing that this does not hide the framework from a determined observer.
const helmet = require('helmet');
app.disable('x-powered-by');
app.use(helmet());
Check the browser’s response headers and confirm HTTPS redirects at the proxy or application layer you selected. Validate redirect destinations against an allowlist, and use parameterized database queries rather than concatenating untrusted input. The official Express security guidance covers TLS, cookies and input handling.
Step 6: Check readiness and shutdown behavior
A health endpoint returns a status a load balancer can use to decide whether the app should receive traffic. The example checks the database because this app needs it to serve requests.
app.get('/health', async (req, res) => {
const ready = await database.ping();
res.sendStatus(ready ? 200 : 503);
});
I ran node readiness_demo.js, which requests /health from a local server:
GET /health -> 200

The 200 status shows the healthy path responded. This small check uses Node’s HTTP server to demonstrate the response flow. Test the Express route and its dependency failure path in your app.
The accompanying Node.js check requests /health and prints its HTTP status. In the app, also test the dependency-failure response. On shutdown, stop accepting connections, let active requests finish within a bound, close clients, then exit so the process manager can restart an unexpected failure.
For deployment performance, set NODE_ENV to production, prefer asynchronous I/O, and place a reverse proxy in front when appropriate. Express’s performance and reliability guide discusses restarts, proxies and scaling. Do not add instances until session state and other shared state work across them.
Also test the route’s contract at its boundaries. For a user lookup, cover an existing identifier, a well-formed identifier with no record, malformed input, and a rejected data lookup. Each case should end with one response path.
A test that only checks the success case can miss a promise rejection that leaves an unhandled error or returns an unintended response.
Express 5 forwards a rejected Promise returned by an async route or middleware to error handling. That does not remove the need to forward errors from callback-style APIs: call next(err) when their callback receives an error. Avoid sending a response and then forwarding the same error, because that can create a second response attempt.
The final error handler should be mounted after routes and other middleware so earlier layers have a chance to handle their own cases. Its four parameters matter to Express’s error-middleware recognition, including the next parameter even when the handler does not use it in every branch. If headers have already been sent, delegate the error rather than trying to replace a response that has started.
Keep client responses generic for unexpected server errors. Log diagnostic context on the server without logging passwords, session secrets, access tokens or full sensitive request bodies. A request identifier can connect a client-safe error response to a server log entry, provided it is generated or validated at a trusted boundary.
For sessions, the development default is not a production storage plan. A process-local in-memory store loses state when that process restarts and cannot provide consistent sessions when requests move between instances. Select a store supported by your deployment, and verify how it persists records, expires them and behaves when unavailable.
Cookie configuration follows the path from the browser to Express. A secure cookie requires Express to recognize HTTPS, including when TLS terminates at a trusted proxy. Match trust proxy to the topology you control, since overly broad trust can make forwarded headers an unsafe source of client or protocol information.
Check the browser’s Set-Cookie response on the deployed HTTPS host, then make a protected request and confirm that the session remains available. If login succeeds but the next request appears anonymous, inspect whether the browser stored and returned the cookie, whether the proxy protocol is recognized, and whether both requests reached a store with the same session data.
This sequence distinguishes cookie delivery from server-side persistence.
Static middleware maps a URL prefix to a directory on disk. Resolve the directory from the application’s file location instead of relying on the process’s current working directory, which can differ under a service manager. Check both the public URL and the deployed artifact: a correct mount cannot serve a file that was omitted from the release.
Place static middleware where it matches the route layout and caching policy. A broad static directory should not expose configuration files or other private material. Keep public assets in a dedicated directory, request a known file through the same host and prefix readers use, and check the response content type as well as the status.
Security middleware is one layer of the review, not a substitute for validating application inputs or protecting secrets. Helmet sets a collection of HTTP response headers, while TLS protects traffic in transit between the browser and the TLS endpoint. Check where TLS ends in your architecture, and make sure any connection from that endpoint to the application follows the deployment’s security requirements.
Disable the X-Powered-By header if you do not want to disclose that framework hint. Treat this as reduced information exposure rather than access control. Validate input at the route boundary, use parameterized database operations, and allowlist redirect destinations so a request parameter cannot send a user to an untrusted site.
A health endpoint should represent whether the instance can do the work it is expected to receive. If the database is required for the app’s core request path, a failed database check can return 503 so an orchestrator or load balancer can stop sending traffic. Optional services should not automatically make the whole app unhealthy when their absence does not prevent core requests.
Separate liveness from readiness when the hosting platform uses both concepts. Liveness answers whether the process should be restarted. Readiness answers whether it should receive new work.
A temporary dependency outage may make an instance unready without proving that restarting the process will help. Consult the hosting platform’s probe semantics before connecting the endpoint to automated restarts.
For graceful shutdown, retain the server returned by app.listen so the process can stop accepting new connections when it receives the configured termination signal. Give active requests a bounded opportunity to finish, close database and other client connections, and then let the process exit.
The timeout should fit the platform’s termination window. Otherwise the platform may kill the process before cleanup completes.
Test shutdown in a non-production environment with a request that remains in progress while the signal is sent. Verify that new traffic is no longer accepted, the active request has the documented outcome, and the process exits before the supervisor’s deadline. Do not test forced termination against live users, and do not confuse a clean shutdown with recovery from an abrupt crash.
Express deployment checks that often fail
Match each symptom to the layer that owns it before changing configuration. These checks distinguish application behavior from proxy, browser and runtime behavior.
| Symptom | Check | Likely correction |
|---|---|---|
| Unknown URL returns an unexpected page | Request an unregistered path | Add a deliberate 404 handler after routes |
| Errors leave requests open | Inspect every middleware branch | Send a response or pass control with next(err) |
| Login works on one instance only | Repeat requests across instances | Use shared session storage and verify affinity when required |
| Cookie absent on HTTPS | Inspect Set-Cookie and proxy setup | Align secure cookie and trust proxy with topology |
| CSS or image returns 404 | Check URL prefix and deployed filesystem | Use an absolute static root and include assets |
| Memory rises over time | Compare process.memoryUsage() over repeated workload | Profile retained objects and release listeners or references |
Keep the health check focused on dependencies needed for requests, rather than optional integrations.
Memory usage alone does not prove a leak: the process can reserve memory for later reuse. Compare repeated workload runs and inspect heap growth alongside resident memory before drawing a conclusion. Node’s process API exposes memory fields for diagnostics.
Use a test environment to simulate an unavailable dependency and a controlled shutdown signal. Check that the health endpoint stops advertising readiness, in-flight requests finish within the configured limit, and the supervisor starts the app again after a forced test failure. Do not test a forced termination against live users.
Conclusion: Verify the whole request path
Use the checks above to decide whether the app can handle its expected traffic. Test routing, sessions, assets, HTTPS and shutdown behavior in the environment that will serve requests.
Continue with Express configuration, EJS templating, routing, and sessions. For a deeper session-store example, see handling Express sessions with Redis. Email delivery is covered in the Node.js email tutorial.
FAQ
These answers cover common deployment questions that need a short decision.
What arguments does Express error middleware take?
It takes (err, req, res, next) and should be mounted after routes and ordinary middleware.
Does Express 5 forward rejected async route handlers?
Yes. Express 5 forwards rejected Promises returned by route handlers and middleware to error handling. Callback APIs must pass errors to next(err).
Can I use the default express-session store in production?
The default in-memory store is not designed for production. Configure a supported shared session store when operating across instances.




