Documentation menuProxy setups: Express

Proxy setups

Proxy the Loogika script with Express

In Express you proxy Loogika with the http-proxy-middleware package. You mount one proxy on a path such as /stats, and it forwards every request under that path to app.loogika.com. The proxy must be registered before any body parser.

Last updated .

What do you need before you start?

You need a Node.js app that runs Express, and your Loogika site ID. Install the proxy package with npm or yarn:

npm install http-proxy-middleware

The examples use version 3 of http-proxy-middleware. Version 3 removed the onProxyReq and onError options, and you now write them under on. The proxy guide explains the idea behind the proxy.

How do you add the Loogika proxy to Express?

Mount the proxy on /stats with https://app.loogika.com/api as its target. Put the block above your body parsers and above your other routes:

// server.js
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
const LOOGIKA_HOST = 'https://app.loogika.com';

// Loogika proxy. Register it before express.json() or any other body parser.
app.use('/stats', createProxyMiddleware({
  target: `${LOOGIKA_HOST}/api`,
  changeOrigin: true,
  on: {
    proxyReq: (proxyReq, req) => {
      // Send the visitor IP to Loogika
      const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
      proxyReq.setHeader('X-Forwarded-For', clientIp);
    },
  },
  logger: console,
}));

// Body parsers go after the proxy
app.use(express.json());

// Your other routes
app.get('/', (req, res) => {
  res.send('Hello World');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Express strips the mount path before the proxy sees the address. A request for /stats/script.js reaches the proxy as /script.js and goes on to https://app.loogika.com/api/script.js. One mount therefore covers every address the Loogika script calls.

The package forwards the browser's request headers unchanged. Loogika's bot detection expects those headers, so do not remove them in the proxyReq handler.

Why must the proxy come before express.json()?

When a body parser runs before the proxy, it consumes the request stream, and the proxy has nothing left to send. Events, user identification and session replay are POST requests, and each of them then reaches Loogika without a body.

Some apps need a parser in front of the proxy. The http-proxy-middleware package exports fixRequestBody for that case. Add fixRequestBody(proxyReq, req) as the last line of your proxyReq handler, and it writes the parsed body back into the request.

The same order rule applies to a catch-all route. A route such as app.get('*', ...) placed above the proxy answers /stats/script.js with your own HTML page.

How do you load the script through the proxy?

Change the address in your script tag to the proxied path, in your HTML or template files:

<script src="/stats/script.js?siteId=YOUR_SITE_ID" defer></script>

Keep the file name script.js. The script works out where its events go by cutting its own address at /script.js. With another file name, every request ends up at a wrong address.

Then switch on First-Party Proxy under Site Settings, General in Loogika. The switch tells Loogika to trust the IP address in the header your proxy sets.

How do you check that the Express proxy works?

Start the server and ask for the script from the command line. The response should have status 200 and a JavaScript content type:

curl -I http://localhost:3000/stats/script.js

Then open the app in a browser and look at the Network tab. The requests to /stats/track should go to your own domain, and your visit should appear in the realtime view in Loogika.

What goes wrong most often with an Express proxy?

SymptomCause and fix
Loogika paths return 404A pathRewrite of '^/stats' never matches on a mounted proxy, because Express has already removed /stats. Put /api in the target instead
Session replay never records, or /stats/track answers with 400The proxy came after a body parser. Move the proxy above the parser, or add fixRequestBody
Every visitor has the location of your serverCheck that the proxyReq handler sets X-Forwarded-For, and that First-Party Proxy is on
Requests hangSet the timeout and proxyTimeout options, for example to 30000 milliseconds

To see where a request goes, log req.originalUrl and proxyReq.path inside the proxyReq handler. The proxy troubleshooting page covers problems that are not specific to Express.

Should you cache or limit proxied requests in Express?

Leave caching to a CDN in front of your app. Loogika already sends a Cache-Control header of one hour on script.js and one day on replay.js, and the proxy passes both through. Because the proxy streams its responses, they pass by any caching middleware built around res.send.

Express body size limits do not apply to the proxied routes either, because the proxy streams request bodies without parsing them. For rate limiting you can put the express-rate-limit package in front of /stats/track.