Extends Express.js with response hooks

Overview

Express Response Hooks

Extend Express.js with response hooks, primarily aimed to manipulate the response before being sent to the client.

Installation

npm install express-response-hooks

Usage

const responseHooks = require('express-response-hooks');

// response hooks initialization
app.use(responseHooks());

// register a middleware that adds a "Cache-Control" header whenever the status code changes
app.use(function (req, res, next) {
    // hook on "statusCode" changes
    res.hooks.on('statusCode', ([ statusCode ]) => {
        if (req.method.toUpperCase() === 'GET') && (statusCode < 400)) {
            res.set('Cache-Control', 'public, max-age=5, s-maxage=31536000');
        }
    });
);

API

require('express-response-hooks')([options])

Creates a middleware that adds hooks to the response object

Options object

  • plugName

    • Type: string
    • Default: "hooks"

    Controls under which key the hooks event emitter will be available in the response object. Default to res.hooks

res.hooks

The hooks EventEmitter that enables registration to the following events:

Event Name Trigger Arguments Array Trigger
"statusCode" res.statusCode status code (int) statusCode property is changed internally
"set" res.set() header name (string), header value (string) set() is called internally or explicitly
"send" res.send() body (int / object / string) send() is called internally (e.g., res.json() calls it twice) or explicitly

For example

res.hooks.once('statusCode', ([ statusCode ]) => {
  // called once when the res.statusCode is changed for the first time
});
res.hooks.on('res', ([ name, value ]) => {
  // called whenever res.res() is called internally by express to set default headers or explicitly
});

Data manipulation

Changing the values in the arguments array will change the arguments passed to the original wrapped property/function

For example

res.hooks.on('res', (args) => {
  const [ name, value ] = args;
  if (name === 'cache-control') {
    // change the value of the header
    args[1] = args[1].replace('public', 'private');
  }
});

res.hooks.bypass

An object with references to the wrapped properties and functions for using them without triggering an event.

For example

res.hooks.on('set', ([ name, value ]) => {
  if (name === 'cache-control') {
    // add additional header without triggering another 'set' event
    res.hooks.bypass.set('cdn-cache-control', value);
  }
});

Notice

  • You should take into consideration that Express internally calls some of the response functions right before the response gets sent to the client (e.g., adding default headers)
  • statusCode manipulation will not work if the hook was triggered by send()
You might also like...

A plugin for Strapi Headless CMS that provides the ability to transform the API request or response.

strapi-plugin-transformer A plugin for Strapi that provides the ability to transform the API request and/or response. Requirements The installation re

Jan 6, 2023

Create a html response with JSX.

Htm Create a text/html response with JSX, powered by Preact and UnoCSS. Usage To use Htm, create a server.tsx file like this: /** @jsx h */ import {

Dec 9, 2022

Uptime monitoring RESTful API server that allows authenticated users to monitor URLs, and get detailed uptime reports about their availability, average response time, and total uptime/downtime.

Uptime Monitoring API Uptime monitoring RESTful API server that allows authenticated users to monitor URLs, and get detailed uptime reports about thei

Jun 14, 2022

a vscode extension for http response data auto transform ts type.

a vscode extension for http response data auto transform ts type.

Api2ts 这是一个自动将 http 的响应数据转化为 ts 的类型,使用 json-to-ts 做的。 Features 框选配置项后,使用快捷键 alt+Q : 请求参数配置文件 在根目录下创建 Api2ts.config.json 文件,配置项如下: { "baseURL": "http

Jun 30, 2022

Pfapi plugin uses local and redis caches to achieve single digit milliseconds on average api response time.

Pfapi plugin uses local and redis caches to achieve single digit milliseconds on average api response time.

Strapi plugin pfapi Pfapi plugin provides configurable, secure and fast API services. APIs are configurable through the admin panel with components an

Sep 17, 2022

A jQuery plugin to submit forms with files via AJAX and to get a response with errors.

jquery-ajaxform A jQuery plugin to submit form with files via AJAX and to get a response with errors. Browsers without FormData uses iframe transport

Mar 30, 2021

A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

HTTPFY curently in beta so you may see problems. Please open a Issue on GitHub and report them! A Incredible fast and Powerful HTTP toolkit Report Bug

Dec 22, 2022

Improve Response Time 10X by Introducing an Interceptor In NestJS

Improve response times 10x by introducing an interceptor in NestJS This sample project demonstrates the usage of interceptors for improving response t

Oct 28, 2022

Modify Request & Response Headers Chrome Extension (Manifest V3)

Modify Request & Response Headers Chrome Extension (Manifest V3)

Modify request & response headers (Chrome Extension Manifest V3) This Chrome extension will add request header and response header to few network requ

Dec 9, 2022

一个基于node.js,express,socket.io的websocket非常棒的聊天室,代码简单很适合新手. A very nice websocket chat room based on node.js, express, socket.io. the code is simple, very suitable for novices

一个基于node.js,express,socket.io的websocket非常棒的聊天室,代码简单很适合新手.  A very nice websocket chat room based on node.js, express, socket.io. the code is simple, very suitable for novices

来来往下看,虽然教程又臭又长但是一步步地保姆式教学很简单的,毕竟我是真菜鸟嘛,当然什么都往细了说╮(╯_╰)╭ 一、使用方法 该教程内容所有指令都为Linux CentOS 7.x环境下指令,其他平台请您自行查询(⊙x⊙;) 1.下载node.js并下载Sakura_Chat_Room node.j

Jul 21, 2022

Socket.io-Express - A simple express project to learn how to use socket.io.

Socket.io-Express - A simple express project to learn how to use socket.io.

Socket.io Express A simple express project to learn how to use socket.io ✨ 👶 Simple project This is a small project that has been designed to be usab

Sep 25, 2022

Express typescript boilerplate using @types/node, @types/express

Express framework boilerplate in typescript.

Sep 21, 2022

An express-ve way to start an express project

Express-ve express starter An express-ve way to start an express project. Checkout a demo project here or Learn how to use express-ve here Are you sta

Mar 28, 2022

React Hooks — 👍

Collaborative editing for your app. Support on Kickstarter! 👍 react-use Collection of essential React Hooks. Port of libreact. Translations: 🇨🇳 汉语

Jan 3, 2023

📋 React Hooks for forms validation (Web + React Native)

📋 React Hooks for forms validation (Web + React Native)

English | 繁中 | 简中 | 日本語 | 한국어 | Français | Italiano | Português | Español | Русский | Deutsch | Türkçe Features Built with performance and DX in mind

Dec 29, 2022

⚛️ Hooks for fetching, caching and updating asynchronous data in React

⚛️ Hooks for fetching, caching and updating asynchronous data in React

Hooks for fetching, caching and updating asynchronous data in React Enjoy this library? Try the entire TanStack! React Table, React Form, React Charts

Jan 9, 2023

React Hooks library for remote data fetching

React Hooks library for remote data fetching

Introduction swr.vercel.app SWR is a React Hooks library for remote data fetching. The name “SWR” is derived from stale-while-revalidate, a cache inva

Jan 4, 2023

⚛️ Hooks for building fast and extendable tables and datagrids for React

⚛️ Hooks for building fast and extendable tables and datagrids for React

Hooks for building lightweight, fast and extendable datagrids for React Enjoy this library? Try them all! React Query, React Form, React Charts Visit

Jan 3, 2023

React Hooks library for remote data fetching

React Hooks library for remote data fetching

Introduction swr.vercel.app SWR is a React Hooks library for remote data fetching. The name “SWR” is derived from stale-while-revalidate, a cache inva

Jan 8, 2023
Releases(v1.0.4)
Owner
Arik
Arik
Waits for HTTP response and retries request until the expected response is received.

Waits for expected HTTP response waitehr (wait [for] expected HTTP response) is a CLI program that waits for HTTP response and retries request until t

Gajus Kuizinas 31 Oct 3, 2022
A javascript library that extends D3.js to enable fast and beautiful visualizations.

d3plus D3plus is a JavaScript re-usable chart library that extends the popular D3.js to enable the easy creation of beautiful visualizations. Installi

D3plus 1.6k Dec 2, 2022
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.

Konva Konva is an HTML5 Canvas JavaScript framework that enables high performance animations, transitions, node nesting, layering, filtering, caching,

konva 8.7k Jan 8, 2023
Extends the default Bootstrap Modal class. Responsive, stackable, ajax and more.

Note: Since this plugin was created to solve a lot of the issues with BS2, it still uses the BS2 markup syntax. Currently I believe the default BS3 mo

Jordan Schroter 5k Dec 28, 2022
Extends UITable making each row a selectable item.

UIPickerTable UIPickerTable is a Scriptable class module that extends UITable making each row a selectable item. -new UIPickerTable Creates an intance

Raymond Velasquez 13 Nov 12, 2022
Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4.

Bootstrap Tooltip Custom Class Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4. Define you

Andrei Victor Bulearca 14 Feb 10, 2022
A tool to check for response status codes with ease

About Archer Archer is an cross-platform tool developed using Nodejs which focuses on the reconnaissance phase of a penetration test. Got a bunch of l

Umair 14 Oct 19, 2022
Simple interactive HTTP response mocker, useful for testing API callouts.

Simple interactive HTTP response mocker, useful for testing API callouts.

null 1 Jul 1, 2022
Ping.js is a small and simple Javascript library for the browser to "ping" response times to web servers in Javascript

Ping.js Ping.js is a small and simple Javascript library for the browser to "ping" response times to web servers in Javascript! This is useful for whe

Alfred Gutierrez 353 Dec 27, 2022
Room impulse response measurement in the browser.

Room impulse response measurement - in the browser! Check it out on danielrudrich.github.io/Broom. Behind the scenes Broom uses the WebAudioAPI to pla

Daniel Rudrich 47 Sep 13, 2022