TS Referer Parser

1.1.0 · active · verified Tue Apr 21

This library provides a typed solution for parsing HTTP referer URLs, classifying them into categories such as search engines, social media, email providers, paid advertising platforms, and notably, AI chatbots. It is currently stable at version 1.1.0, with minor releases occurring periodically to introduce new features, expand database coverage, and address maintenance. A key differentiator is its comprehensive referer database, which is compiled from both Snowplow's referer-parser and Matomo's searchengine-and-social-list, covering over 450 sources. Recent updates significantly expanded its AI/chatbot detection capabilities to include popular models like ChatGPT, Claude, and Google Gemini, alongside broader social media coverage for platforms like X (formerly Twitter) and Bluesky. The library offers full TypeScript support, ensuring type inference, and is designed to work in both client-side (browser) and server-side (Node.js) JavaScript environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse various types of referer URLs, including direct traffic, social media, search engines, and AI chatbots, showing how to obtain the referer string in both browser and Node.js environments.

import { parse, Referer } from "ts-referer-parser";

// Determine referer URL based on environment
let refererUrl: string | null = null;
let currentPageUrl: string = 'http://www.example.com/'; // Your current page URL

if (typeof window !== 'undefined' && window.document) {
  // Client-side (browser) environment
  refererUrl = window.document.referrer;
  currentPageUrl = window.location.href;
} else {
  // Server-side environment (e.g., Node.js with Express)
  // In a real application, 'request' would come from your HTTP server context.
  // For this example, we'll simulate it.
  const request = { headers: { referer: 'https://www.google.com/search?q=example' } };
  refererUrl = request.headers.referer || null;
}

// Example 1: Direct traffic
let result: Referer = parse(null, currentPageUrl);
console.log("Direct traffic:", result); // Expected: { medium: 'direct', referer: null, term: null }

// Example 2: Social media referral
result = parse(
  "https://www.facebook.com/somepage",
  currentPageUrl
);
console.log("Social media referral:", result); // Expected: { medium: 'social', referer: 'Facebook', term: null }

// Example 3: Search engine referral with search term
result = parse(
  "http://www.google.com/search?q=typescript+parser&hl=en",
  currentPageUrl
);
console.log("Search engine referral:", result); // Expected: { medium: 'search', referer: 'Google', term: 'typescript parser' }

// Example 4: AI Chatbot referral (new in v1.1.0)
result = parse(
  "https://chatgpt.com/c/12345",
  currentPageUrl
);
console.log("AI Chatbot referral:", result); // Expected: { medium: 'chatbot', referer: 'ChatGPT', term: null }

view raw JSON →