Environment Variables, Configuration, Logging, and Centralized Error Handling

Validate configuration at startup and correlate access logs with error responses using request IDs

🎯 Introduction

By the end of this article, you will be able to configure ports through environment variables, log API requests automatically, and investigate failures by request ID.

⚙️ Read configuration at startup

Create config.mjs to read the port and validate its range:

config.mjs
const port = Number(process.env.PORT ?? 3000);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
    throw new Error('PORT must be an integer from 1 to 65535');
}
export const config = { port };

An absent PORT defaults to 3000; abc stops startup. Check required settings such as database addresses and keys for missing values. Do not provide publicly known default secrets.

A local .env can contain:

.env
PORT=3000

Load it with node --env-file=.env and keep real credentials out of the repository. Deployment platforms can also inject environment variables directly.


📝 Log requests with middleware

pino-http logs request response statuses and durations:

npm install pino-http@11.0.0

Create logging-app.mjs:

logging-app.mjs
import express from 'express';
import pinoHttp from 'pino-http';
import { randomUUID } from 'node:crypto';

export const app = express();

Register logging middleware before routes:

logging-app.mjs
app.use(pinoHttp({
    genReqId: () => randomUUID(),
    redact: ['req.headers', 'req.url', 'req.query', 'req.params', 'res.headers'],
    customProps: req => ({ path: req.path })
}));

genReqId generates a request ID. redact hides complete headers, URLs, and parameters to avoid logging Cookie, Authorization, or query secrets. path separately records the path without query parameters. Request bodies are not logged by default; do not add password forms to logs yourself.


🏷 Return the request ID to clients

Continue with:

logging-app.mjs
app.use((req, res, next) => {
    res.setHeader('X-Request-Id', req.id);
    next();
});

The frontend can include this response header's ID in problem reports so the server can locate matching logs. Cross-origin scripts also need X-Request-Id in cors's exposedHeaders to read it.


🧯 Log exceptions and expose limited information

Add two endpoints: one succeeds, and the other exercises the failure path:

logging-app.mjs
app.get('/health', (req, res) => res.json({ status: 'ok' }));
app.get('/failure', async (req, res) => {
    throw new Error('Simulated internal operation failure');
});

Register error middleware after them:

logging-app.mjs
app.use((error, req, res, next) => {
    if (res.headersSent) return next(error);
    req.log.error({ err: error }, 'Request processing failed');
    res.status(500).json({ error: 'The service is temporarily unable to process the request' });
});

req.log automatically associates the current request. Clients receive only a generic message, while the server can inspect internal errors. To also handle JSON and other input errors, place this log call in the appropriate branch from the shared exception handling article. Avoid registering several response-sending error handlers redundantly.


🚀 Start with configuration and verify logs

Create logging-server.mjs:

logging-server.mjs
import { app } from './logging-app.mjs';
import { config } from './config.mjs';

app.listen(config.port, '127.0.0.1');

Run:

node --env-file=.env logging-server.mjs

/health returns 200 and produces an access log with status and duration. /failure returns 500; the response header ID matches the error log's request ID. Log duration measures server processing time, not the entire interval from a page click to completed rendering.


❓ Questions and Answers

Q1: Would logging every request detail make investigation easier?

It may expose passwords and tokens. Log only necessary fields and control log access and retention.

Q2: Should every business function log an error?

No. Log the same exception at its final handling point to avoid duplication.

Q3: Must production use a .env file?

No. Environment variables injected by the deployment platform are also available through process.env.


🧪 Practice

Set PORT to abc and confirm startup fails. Restore it, request /failure, and match the response ID with the error log.

// Record your results here