Search
⌘K

Express Utils

Utilities for working with express.js.

Example Usage

import { getExpressRequestInfo } from './express.utils';

const reqInfo = getExpressRequestInfo(
  req,
  res,
  'an-id-for-this-request-used-only-by-you-to-identify-it',
);
// ⏬
{
  reqData: {
    id: 'an-id-for-this-request-used-only-by-you-to-identify-it',
    origin: 'http://localhost:3000',
    method: 'GET',
    hostname: 'localhost',
    path: '/api',
    query: {},
    full_url: 'http://localhost:3000/api',
    headers: {},
  },
  resData: {
    statusCode: 200,
    statusMessage: 'OK',
    responseTime: 'responseTime' in res ? res.responseTime : 'unknown',
    headers: ('_header' in res && typeof res._header === 'string') ? res._header.split('\n') : 'unknown',
  },
}

Dependencies

npmexpress

Auto Install

npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-express-utils.json

Manual Install

express.utils.ts
/**
 * Source: http://localhost:3000
 */

import type {
  Request as ExpressRequest,
  Response as ExpressResponse,
} from 'express';

export const getExpressRequestInfo = (
  req: ExpressRequest,
  res: ExpressResponse,
  reqId: string,
) => {

  // get request data
  const isHostLocalhost = req.hostname === 'localhost' || req.hostname.startsWith('192.168.');
  const reqData = {
    id: reqId,
    origin: req.headers.origin,
    method: req.method,
    hostname: req.hostname,
    path: req.path,
    query: req.query,
    full_url: [
      req.protocol,
      "://",
      req.hostname,
      isHostLocalhost ? `:${req.socket.localPort}` : '',
      req.originalUrl,
    ].join(''),
    headers: req.headers,
  };

  // get response data
  const resData = {
    statusCode: res.statusCode,
    statusMessage: res.statusMessage,
    responseTime: 'responseTime' in res ? res.responseTime : 'unknown',
    headers: ('_header' in res && typeof res._header === 'string') ? res._header.split('\n') : 'unknown',
  };

  return {
    reqData,
    resData,
  };
};

Test

No test

Command Palette

Search for a command to run...