As everyone knows redux works by listening and reacting to actions. These actions can be anything such as "my-app/HELP_BUTTON_CLICK". Assuming you are using redux correctly and dispatching actions for all user interactions there should be nothing stopping us from tapping into redux to see if we can add some usage tracking.
Turns out this is very easy to do in redux. All you need is a custom redux middleware. An example of a redux middleware is outlined below
import {Middleware, Store} from 'redux';
export const reduxNewRelicMiddleware: Middleware = (store: Store<any>) => (next) => (action) => {
console.log(action);
return next(action);
};
A redux middleware is basically a curried function. The above is an example of a very simple middleware. All it does is listen to every dispatched action and then logs the action to the console. You can activate this middleware using the code below.
const middleware: any = [];
if (environment.production) { // Only want this active on production
middleware.push(reduxNewRelicMiddleware);
}
So now we know how to make our first redux middleware, and we know our app using redux correctly which means we should have loads of actions being dispatched, so in theory we should be able to send every dispatched event back to our new-relic server for instant usage tracking goodness of our entire app. Turns out we can and its very simple. Assuming you have new relic in your app already, we should be able to simply call addPageAction and send all dispatched actions to the backend
import {Middleware, Store} from 'redux';
interface CustomWindow extends Window {
newrelic: any;
}
declare let window: CustomWindow;
export const reduxNewRelicMiddleware: Middleware = (store: Store<any>) => (next) => (action) => {
if (window.newrelic) {
window.newrelic.addPageAction(action.type, action);
}
return next(action);
};
One thing to note is that addPageAction will not send a request immediately to the back-end, instead it accumulates all the actions over a period of time and then batch uploads them to the server
Now that our app is sending all actions to new relic we can go to the dashboard and query our actions. For example say we want to get a count of how many times our help button was clicked in the last 24 hours we could simply use the following query
SELECT count(*) FROM PageAction WHERE actionName='my-app/HELP_BUTTON_CLICK' SINCE 24 hours ago