nodejs

typescript
import type { IncomingMessage, ServerResponse } from "http";

const MIN_BYTES = 1024;

const INCOMPRESSIBLE = /^(image|video|audio)\/|application\/(zip|gzip|x-brotli|pdf|octet-stream)/i;

Response compression (only when it helps)

performance http express
by codesnips 3 tabs
typescript
import pino, { Logger } from 'pino';
import { AsyncLocalStorage } from 'node:async_hooks';

export interface Store {
  requestId: string;
  logger: Logger;

Request ID + structured logging (Express + pino)

express logging observability
by codesnips 3 tabs
typescript
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { Resource } from '@opentelemetry/resources';
import {

OpenTelemetry tracing for Node HTTP

observability tracing opentelemetry
by codesnips 3 tabs
typescript
import { Agent as HttpAgent } from 'http';
import { Agent as HttpsAgent } from 'https';

const shared = {
  keepAlive: true,
  keepAliveMsecs: 1_000,

HTTP keep-alive agent for outbound calls

http performance nodejs
by codesnips 3 tabs
typescript
import express, { Express, NextFunction, Request, Response } from 'express';
import { userRoutes } from './userRoutes';

function authenticate(req: Request, res: Response, next: NextFunction) {
  const header = req.header('authorization');
  if (!header || !header.startsWith('Bearer ')) {

Testing Express routes with Supertest + Jest

testing express supertest
by codesnips 4 tabs
typescript
import { z } from "zod";

const booleanFromString = z.preprocess((val) => {
  if (typeof val !== "string") return val;
  return ["true", "1", "yes", "on"].includes(val.toLowerCase());
}, z.boolean());

Typed env parsing with zod

typescript zod validation
by codesnips 3 tabs
typescript
import crypto from 'crypto';
import helmet from 'helmet';
import type { Express, Request, Response, NextFunction } from 'express';

function cspNonce(req: Request, res: Response, next: NextFunction): void {
  res.locals.cspNonce = crypto.randomBytes(16).toString('base64');

Security headers with helmet (baseline hardening)

security express helmet
by codesnips 3 tabs
typescript
import crypto from 'crypto';

interface VerifyOptions {
  rawBody: Buffer;
  signatureHeader: string | undefined;
  secret: string;

Webhook signature verification (timing-safe compare)

security webhooks hmac
by codesnips 3 tabs
typescript
import { JSDOM } from 'jsdom';
import createDOMPurify, { DOMPurifyI } from 'dompurify';

const { window } = new JSDOM('');
const DOMPurify: DOMPurifyI = createDOMPurify(window as unknown as Window);

Sanitize user HTML safely (DOMPurify + JSDOM)

security html dompurify
by codesnips 2 tabs
javascript
const crypto = require('crypto');

function computeSignature(secret, timestamp, payload) {
  return crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.${payload}`, 'utf8')

Verify Stripe-Style Webhook Signatures With HMAC in Express Before Processing

webhooks hmac security
by codesnips 2 tabs
typescript
import { Writable } from "node:stream";
import type { Pool } from "pg";

interface Row {
  email: string;
  name: string;

Streaming CSV import (Node streams)

streams postgres nodejs
by codesnips 3 tabs
typescript
const rawOrigins = process.env.ALLOWED_ORIGINS ?? "";

export const allowedOrigins = new Set(
  rawOrigins
    .split(",")
    .map((o) => o.trim())

CORS configuration that’s explicit (no *)

security http express
by codesnips 3 tabs