Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/ga4-server-destination.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@walkeros/server-destination-ga4': minor
---

New GA4 Measurement Protocol server destination. Server events join the
visitor's GA4 session when the `_ga` client id and session id are mapped; an
event without a client id gets a stable one derived from its event id. Ad
signals follow the event's marketing consent, `timestamp_micros` is sent for
events under 72 hours, and invalid event names fail before any request.
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions packages/server/destinations/ga4/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<p align="left">
<a href="https://www.walkeros.io">
<img alt="walkerOS" title="walkerOS" src="https://www.walkeros.io/img/walkerOS_logo.svg" width="256px"/>
</a>
</p>

# @walkeros/server-destination-ga4

Server-side events to Google Analytics 4 through the Measurement Protocol:
conversions and other server events join the visitor's GA4 session when the
`_ga` client id and session id are mapped.

[Documentation](https://www.walkeros.io/docs/destinations/server/ga4) &bull;
[NPM Package](https://www.npmjs.com/package/@walkeros/server-destination-ga4)
&bull;
[Source Code](https://github.com/elbwalker/walkerOS/tree/main/packages/server/destinations/ga4)

## Installation

```bash
npm install @walkeros/server-destination-ga4
```

## Quick start

```json
{
"version": 4,
"flows": {
"default": {
"config": { "platform": "server" },
"destinations": {
"ga4": {
"package": "@walkeros/server-destination-ga4",
"config": {
"settings": {
"measurementId": "G-XXXXXXXXXX",
"apiSecret": "$secret.GA4_API_SECRET"
}
}
}
}
}
}
}
```

This quick start sets no consent: add `consent: { analytics: true }` to `config`
before you go live, see the docs.

## Documentation

Full configuration, mapping, and examples live in the docs:
**https://www.walkeros.io/docs/destinations/server/ga4**

## Contribute

Feel free to contribute by submitting an
[issue](https://github.com/elbwalker/walkerOS/issues), starting a
[discussion](https://github.com/elbwalker/walkerOS/discussions), or getting in
[contact](https://calendly.com/elb-alexander/30min).

## License

MIT
5 changes: 5 additions & 0 deletions packages/server/destinations/ga4/jest.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import baseConfig from '@walkeros/config/jest';

const config = {};

export default { ...baseConfig, ...config };
76 changes: 76 additions & 0 deletions packages/server/destinations/ga4/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"name": "@walkeros/server-destination-ga4",
"description": "Google Analytics 4 Measurement Protocol server destination for walkerOS",
"version": "4.9.0",
"license": "MIT",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./dev": {
"types": "./dist/dev.d.ts",
"import": "./dist/dev.mjs",
"require": "./dist/dev.js"
},
"./walkerOS.json": "./dist/walkerOS.json",
"./examples": {
"types": "./dist/examples/index.d.ts",
"import": "./dist/examples/index.mjs",
"require": "./dist/examples/index.js"
}
},
"files": [
"dist/**",
"CHANGELOG.md"
],
"scripts": {
"build": "tsup --silent",
"clean": "rm -rf .turbo && rm -rf dist",
"dev": "jest --watchAll --colors",
"typecheck": "tsc --noEmit",
"lint": "eslint \"**/*.ts*\"",
"test": "jest",
"update": "npx npm-check-updates -u && npm update"
},
"dependencies": {
"@walkeros/core": "4.9.0",
"@walkeros/server-core": "4.9.0"
},
"devDependencies": {
"@walkeros/collector": "4.9.0"
},
"repository": {
"url": "git+https://github.com/elbwalker/walkerOS.git",
"directory": "packages/server/destinations/ga4"
},
"author": "elbwalker <hello@elbwalker.com>",
"homepage": "https://github.com/elbwalker/walkerOS#readme",
"bugs": {
"url": "https://github.com/elbwalker/walkerOS/issues"
},
"walkerOS": {
"type": "destination",
"platform": [
"server"
],
"docs": "https://www.walkeros.io/docs/destinations/server/ga4"
},
"keywords": [
"walkerOS",
"walkerOS-destination",
"destination",
"server",
"ga4",
"google-analytics",
"measurement-protocol",
"analytics"
],
"funding": [
{
"type": "GitHub Sponsors",
"url": "https://github.com/sponsors/elbwalker"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import path from 'path';
import { conformance } from '@walkeros/collector/dev';
import { destinationGA4 } from '..';
import { examples, schemas } from '../dev';

describe('ga4 conformance', () => {
beforeEach(() => {
jest.useRealTimers();
});

it('conforms', async () => {
await conformance('destination', destinationGA4, {
profile: 'http',
examples: examples.step,
schema: schemas.settings,
settings: examples.minimal.settings,
minimal: examples.minimal,
root: path.join(__dirname, '..', '..'),
});
});
});
161 changes: 161 additions & 0 deletions packages/server/destinations/ga4/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import type { Collector, WalkerOS } from '@walkeros/core';
import type { Settings } from '../types';
import {
clone,
createMockContext,
createMockLogger,
getEvent,
} from '@walkeros/core';
import { destinationGA4 as destination } from '..';
import { fallbackClientId } from '../push';
import { examples } from '../dev';

describe('Server Destination GA4 Measurement Protocol', () => {
const settings: Settings = { measurementId: 'G-TEST123', apiSecret: 'a&b' };
const mockSendServer = jest.fn();
const testEnv = clone(examples.env.push);
testEnv.sendServer = mockSendServer;

const body = () => JSON.parse(mockSendServer.mock.calls[0][1]);

function event(props: Partial<WalkerOS.Event> = {}): WalkerOS.Event {
return getEvent('order complete', {
id: 'ev-1',
timestamp: 1700000900000,
consent: {},
...props,
});
}

async function push(
walkerEvent: WalkerOS.Event,
data: Record<string, unknown> = {},
extra: Partial<Settings> = {},
rule?: Record<string, unknown>,
) {
return destination.push(
walkerEvent,
createMockContext({
config: { settings: { ...settings, ...extra } },
data,
env: testEnv,
...(rule ? { rule } : {}),
}),
);
}

async function init(config: Record<string, unknown>) {
return destination.init({
config: { settings: config as unknown as Settings },
collector: {} as Collector.Instance,
env: testEnv,
logger: createMockLogger(),
id: 'test-ga4',
});
}

beforeEach(() => {
jest.clearAllMocks();
mockSendServer.mockResolvedValue({ data: {} });
});

test('init checks measurementId and apiSecret', async () => {
await expect(init({})).rejects.toThrow(
'Config settings measurementId, apiSecret missing',
);
await expect(
init({ measurementId: 'UA-1', apiSecret: 'x' }),
).rejects.toThrow('must look like G-XXXX');
});

test('endpoint carries encoded measurement id and secret', async () => {
await push(event());
expect(mockSendServer.mock.calls[0][0]).toBe(
'https://www.google-analytics.com/mp/collect?measurement_id=G-TEST123&api_secret=a%26b',
);
});

test('custom url (EU collection)', async () => {
await push(
event(),
{},
{
url: 'https://region1.google-analytics.com/mp/collect',
},
);
expect(mockSendServer.mock.calls[0][0]).toMatch(
/^https:\/\/region1\.google-analytics\.com\/mp\/collect\?/,
);
});

test('event name: spaces become _, invalid names fail', async () => {
await push({ ...event(), name: 'order complete' });
expect(body().events[0].name).toBe('order_complete');
mockSendServer.mockClear();
await expect(
push({ ...event(), name: '1 bad-name' }),
).rejects.toMatchObject({ code: 'mapping', retryable: false });
expect(mockSendServer).not.toHaveBeenCalled();
});

test('valid client id and session id are kept', async () => {
await push(event(), { client_id: '123.456', session_id: 1699999000 });
expect(body().client_id).toBe('123.456');
expect(body().events[0].params.session_id).toBe('1699999000');
});

test('malformed client id and session id are replaced or dropped', async () => {
await push(event(), { client_id: 'GA1.1.123.456', session_id: 'abc' });
expect(body().client_id).toBe(await fallbackClientId(event()));
expect(body().events[0].params).not.toHaveProperty('session_id');
});

test('fallback client id is stable per event id', async () => {
const a = await fallbackClientId(event());
const b = await fallbackClientId(event());
expect(a).toBe(b);
expect(a).toMatch(/^\d+\.1700000900$/);
expect(await fallbackClientId(event({ id: 'ev-2' }))).not.toBe(a);
});

test('value is a number, an invalid one is dropped', async () => {
await push(event(), { params: { value: '19.9', currency: 'EUR' } });
expect(body().events[0].params.value).toBe(19.9);
mockSendServer.mockClear();
await push(event(), { params: { value: 'n/a' } });
expect(body().events[0].params).not.toHaveProperty('value');
});

test('ad signals follow the marketing consent', async () => {
await push(event({ consent: { marketing: true } }));
expect(body().consent).toEqual({
ad_user_data: 'GRANTED',
ad_personalization: 'GRANTED',
});
mockSendServer.mockClear();
await push(event({ consent: { analytics: true } }));
expect(body().consent.ad_user_data).toBe('DENIED');
});

test('timestamp_micros only for events under 72 hours', async () => {
const recent = Date.now() - 1000;
await push(event({ timestamp: recent }));
expect(body().timestamp_micros).toBe(recent * 1000);
mockSendServer.mockClear();
await push(event());
expect(body()).not.toHaveProperty('timestamp_micros');
});

test('user_id only when a non-empty string', async () => {
await push(event(), { user_id: 'u1' });
expect(body().user_id).toBe('u1');
mockSendServer.mockClear();
await push(event(), { user_id: '' });
expect(body()).not.toHaveProperty('user_id');
});

test('silent rule sends nothing', async () => {
await push(event(), {}, {}, { silent: true });
expect(mockSendServer).not.toHaveBeenCalled();
});
});
Loading