floatdrop / express-request-id

Middleware for setting unique request id
MIT License
120 stars 24 forks source link

Consider Cuid2 support? #41

Open ericelliott opened 1 year ago

ericelliott commented 1 year ago

Cuid2 is a secure id generator that may be better than UUID for this use case.

Cuid2 is:

UUID V4 relies purely on pseudorandom entropy (even the "cryptographically secure" version - see Cuid2 docs), and has historically had collision problems, which could lead to duplicate request ids.

masterkain commented 3 months ago
// src/libs/express-unique-id.ts
import { Request, Response, NextFunction, RequestHandler } from 'express';
import { createId } from '@paralleldrive/cuid2';

export interface ExpressRequestIdOptions {
  setHeader?: boolean;
  headerName?: string;
  generator?: () => string;
  validator?: (id: string) => boolean;
}

export function requestID(options: ExpressRequestIdOptions = {}): RequestHandler {
  const { generator = createId, headerName = 'X-Request-Id', setHeader = true, validator = () => true } = options;

  return function (req: Request, res: Response, next: NextFunction) {
    let requestId = req.get(headerName);

    // Use the validator to check if the existing ID is acceptable
    if (!requestId || !validator(requestId)) {
      requestId = generator();
    }

    Object.defineProperty(req, 'id', {
      value: requestId,
      writable: false,
    });

    if (setHeader) {
      res.setHeader(headerName, requestId);
    }

    next();
  };
}
import { requestID } from '@/libs/express-unique-id';
app.use(requestID());

also includes a validator for https://github.com/floatdrop/express-request-id/issues/39