VENNStart
Guide

Getting my Express TypeScript API ready for production

Sosifie's Express API in production: error handling, validation, express-rate-limit behind a proxy, helmet, Docker, and an if that stopped the server listening.

Lê Anh Tuấn4 min read

Adding /healthz to Sosifie's API, I also wrapped index.ts in an if that only called listen() when NODE_ENV wasn't production. On the server the process ran its imports but never opened the port, the cron jobs in the listen callback never started, and that if stayed for about three weeks. The API is Express 4 in TypeScript, with Prisma on Postgres plus Socket.IO. Versions come from the lockfile (Express 4.22, express-rate-limit 8.5, helmet 8.2, TypeScript 5.9, Jest 30).

Split app.ts from index.ts

That guard belongs to serverless setups, where the platform imports your app. On a normal server it serves nobody. app.ts (the Express app) was already separate from index.ts (HTTP server, Socket.IO, listen, signals). The bug stayed in one file, and Supertest imports app without opening a port. I'd split every Express project that way from day one. Socket.IO has its own post.

The rest is boring on purpose. Each route declares its middleware chain, and a controller reads req and hands off to a service that talks to Prisma. Services never touch req or res. They can't call the translation function, so whatever they throw has to be something the outer layer can translate.

Async errors and input

Express 4 doesn't catch a rejected promise in an async handler. Without next(err) you get an unhandled rejection and no response. Sosifie uses both express-async-errors and an asyncHandler wrapper where one would do. Express 5 calls next(err) itself, and upgrading removes both. If I wrote it again, I'd throw message keys instead of English sentences:

import type { ErrorRequestHandler } from 'express';

export class AppError extends Error {
  constructor(
    public readonly statusCode: number,
    public readonly messageKey: string,
    public readonly details?: unknown,
  ) {
    super(messageKey);
  }
}

export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
  if (res.headersSent) return next(err);

  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      success: false,
      error: req.t(err.messageKey),
      details: err.details,
    });
  }

  req.log.error({ err }, 'unhandled error'); // full detail goes to logs only
  res.status(500).json({ success: false, error: req.t('common.error') });
};

Unexpected errors return a generic sentence, with details only in the log. Express's default handler does the same in production, and a custom one that leaks more is pointless.

Validation uses express-validator, but types are defined elsewhere and controllers write req.query.limit as string. TypeScript believes that cast. If I redid it, I'd use zod so the schema both checks and types the input, including query and params:

import type { RequestHandler } from 'express';
import type { ZodType } from 'zod';

type Schemas = { body?: ZodType; query?: ZodType; params?: ZodType };

export const validate = (schemas: Schemas): RequestHandler => (req, res, next) => {
  for (const part of ['body', 'query', 'params'] as const) {
    const schema = schemas[part];
    if (!schema) continue;
    const result = schema.safeParse(req[part]);
    if (!result.success) {
      return res.status(400).json({
        success: false,
        error: req.t('common.invalid_input'),
        issues: result.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
      });
    }
    res.locals[part] = result.data; // req.query is read-only in Express 5
  }
  next();
};

// router.get('/', validate({ query: z.object({ limit: z.coerce.number().int().min(1).max(50).default(10) }) }), list)

Rate limiting behind a proxy

The general limiter allows 1000 requests per 15 minutes, auth gets 15 per 15 minutes, and content creation 20 per minute. The default key is req.ip. Behind a proxy with trust proxy left at false, Express sees the proxy's IP, and the whole app shares one bucket.

Setting it to true is wrong too. Express then takes the leftmost X-Forwarded-For entry, which the client controls, and anyone can bypass the limiter with a fake IP (the library warns with ERR_ERL_PERMISSIVE_TRUST_PROXY). The right value is the number of real proxies in front of the app:

import express from 'express';
import { rateLimit } from 'express-rate-limit';

const app = express();
app.set('trust proxy', 1); // number of proxies in front of the app, not `true`

const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  limit: 15, // `max` still works, `limit` is the current name
  standardHeaders: 'draft-8',
  legacyHeaders: false,
  message: (req: express.Request) => ({ success: false, error: req.t('auth.too_many_attempts') }),
});

// Temporary: compare this with your real public IP, then delete it
app.get('/ip', (req, res) => res.send(req.ip));

The /ip route is from express-rate-limit's troubleshooting page. Compare it with your public IP after deploying, raise the number until they match, then delete it. If your host has two paths in with different hop counts (through a CDN and direct), the right count for one is spoofable on the other. Version 8 groups IPv6 by /56 subnet, and the default store is per-process memory, so multiple instances need rate-limit-redis.

Languages, headers, CORS and health checks

Messages live in locales/en.ts and locales/vi.ts, and the Vietnamese file is typed as typeof en. A missing key fails the build. The middleware picks Vietnamese whenever Accept-Language contains vi, even en-US,en;q=0.9,vi;q=0.1. req.acceptsLanguages('en', 'vi') reads quality values and would fix that. The middleware already runs before the limiters, but their messages are hard-coded English strings, so they need a message function like the one above to get translated.

helmet() defaults cover most headers, including CSP and a one-year HSTS, and remove X-Powered-By. CORS enables credentials because auth uses cookies. The old origin callback returned new Error('Not allowed by CORS'), which turned unknown origins into 500s. callback(null, false) just omits the headers and leaves blocking to the browser.

GET /healthz is outside the API prefix, skips rate limiting and never touches the database. That's right for liveness, since a slow second from Postgres is no reason to restart. For readiness, add an endpoint that runs SELECT 1.

tsconfig and Docker

In one night tsconfig went through CommonJS, Node16 and ESNext + Bundler before settling on Node16. Without "type": "module", Node runs the output as CommonJS, and ESNext + Bundler puts import statements in it. With Node16 the output still uses require, but dynamic import() stays a real ESM import and needs full paths, so await import('../utils') became await import('../utils/index.js').

For a while the output went to dist/src/index.js. Without rootDir, tsc uses the common root of all inputs, and the Swagger config's import of ../../package.json pushed that root up a level:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "node16",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "sourceMap": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["**/*.test.ts", "**/*.spec.ts"]
}

tsx in dev strips types without checking them, so run tsc --noEmit in CI. express-async-errors once sat in devDependencies, and with --omit=dev that crashes on the first require.

The current Dockerfile uses two stages on node:20-alpine, and mine would add a non-root user, a healthcheck and exec:

FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
COPY prisma ./prisma/
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production PORT=8080
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/prisma ./prisma
USER node
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1
CMD ["sh", "-c", "npx prisma migrate deploy && exec node dist/index.js"]

Without exec, the shell is PID 1 and your SIGTERM handler may never get the signal. DevDependencies still end up in the image because the Prisma CLI is one and migrate deploy runs at startup. I'd move migrations to a release step rather than add prisma to dependencies.

swagger-jsdoc globs ./src/routes/*.ts at startup, but the runner stage only has dist/. tsc keeps comments, so point the glob at the compiled files.

What mocked tests catch

Tests use Jest with ts-jest, Supertest against app, and mockDeep<PrismaClient>() from jest-mock-extended, plus a moduleNameMapper for the .js import suffixes. Mocked tests catch wiring mistakes and wrong status codes or response shapes. A wrong Prisma query passes. I think a few tests against real Postgres in a container would catch more than a dozen more mocks, but the repo has none yet.

  • Express
  • TypeScript
  • Node.js
  • Docker
  • Prisma
  • Backend

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.