Express.js
Track referral clicks, leads, and sales in an Express.js REST API.
Prerequisites
- Node.js 18+ with Express.js
- A Refport account and API key (Settings → API Keys)
- A referral program created in the dashboard
Install refport-js and serve it to your frontend, or include the manual CDN script in your HTML template. The script reads refp_id from the URL and stores it in a cookie.
npm install refport-jsIf your Express app serves HTML, add the manual tracking script to the <head> of your base template:
<script
src="https://cdn.jsdelivr.net/npm/refport-js@0.4.0/dist/auto.iife.js"
defer
data-query-param="refp_id"
data-cookie-name="refp_id"
></script>Or if you bundle your frontend separately, import and call init() once in your entry file:
import { init } from "refport-js";
init();Install the Node.js SDK and create a shared singleton module.
npm install refportimport { Refport } from "refport";
export const refport = new Refport({
apiKey: process.env.REFPORT_API_KEY!,
});Add REFPORT_API_KEY to your .env and load it with dotenv before starting the server.
Create a small middleware that reads the refp_id cookie and attaches it to req so any route can access it without repeating the cookie parsing logic.
import { type NextFunction, type Request, type Response } from "express";
import { getClickIdFromCookie } from "refport";
declare global {
namespace Express {
interface Request {
clickId?: string | null;
}
}
}
export function extractClickId(
req: Request,
_res: Response,
next: NextFunction
) {
req.clickId = getClickIdFromCookie(req.headers.cookie);
next();
}Register it globally in your app entry:
import express from "express";
import { extractClickId } from "./middleware/clickId";
const app = express();
app.use(express.json());
app.use(extractClickId);Call refport.track.lead() after a user is created, using the click ID attached by the middleware.
import { Router } from "express";
import { refport } from "../lib/refport";
const router = Router();
router.post("/register", async (req, res) => {
const user = await createUser(req.body);
try {
if (req.clickId) {
await refport.track.lead({
clickId: req.clickId,
eventName: "Sign Up",
customerExternalId: user.id,
customerEmail: user.email,
customerName: user.name,
});
}
} catch {
/* tracking failure must never block registration */
}
res.json(user);
});
export default router;import { Router } from "express";
import { refport } from "../lib/refport";
const router = Router();
router.post("/complete", async (req, res) => {
const order = await completeOrder(req.body);
try {
if (req.clickId) {
await refport.track.sale({
clickId: req.clickId,
customerExternalId: order.userId,
amount: order.amountCents,
currency: "usd",
eventName: "Purchase",
invoiceId: order.invoiceId,
paymentProcessor: "stripe",
});
}
} catch {
/* tracking failure must never block order processing */
}
res.json(order);
});
export default router;