This commit is contained in:
55
packages/react/CHANGELOG.md
Normal file
55
packages/react/CHANGELOG.md
Normal file
@@ -0,0 +1,55 @@
|
||||
## 0.3.5
|
||||
|
||||
## 0.4.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 0eb5c9f: react 19 as peer dep
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 7ea8c11: fix: events tracked at page load are sometimes not sent
|
||||
|
||||
## 0.3.4
|
||||
|
||||
- Move browser locale and is debug reads from import to first event to better support SSR
|
||||
|
||||
## 0.3.3
|
||||
|
||||
- Rename `apiPath` to `apiUrl`
|
||||
|
||||
## 0.3.2
|
||||
|
||||
- Fix error when running on chrome
|
||||
|
||||
## 0.3.1
|
||||
|
||||
- Support for custom API path
|
||||
|
||||
## 0.3.0
|
||||
|
||||
- Internal refactor
|
||||
|
||||
## 0.2.2
|
||||
|
||||
- Updated dependencies
|
||||
|
||||
## 0.2.1
|
||||
|
||||
- Updated dependencies
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Updated dependencies
|
||||
|
||||
## 0.1.2
|
||||
|
||||
- Fixed an issue with client-side checking
|
||||
|
||||
## 0.1.1
|
||||
|
||||
- Remove warning log from Server Side Rendering
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Initial version of the React SDK for Aptabase
|
||||
21
packages/react/LICENSE
Normal file
21
packages/react/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Sumbit Labs Ltd.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
154
packages/react/README.md
Normal file
154
packages/react/README.md
Normal file
@@ -0,0 +1,154 @@
|
||||

|
||||
|
||||
# Aptabase SDK for React Apps
|
||||
|
||||
A tiny SDK (1 kB) to instrument your React apps with Aptabase, an Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install the SDK using npm or your preferred JavaScript package manager
|
||||
|
||||
```bash
|
||||
npm add @aptabase/react
|
||||
```
|
||||
|
||||
2. Get your `App Key` from Aptabase, you can find it in the `Instructions` menu on the left side menu.
|
||||
|
||||
3. Initialize the `AptabaseProvider` component to your app based on your framework.
|
||||
|
||||
<details>
|
||||
<summary>Setup for Next.js (App Router)</summary>
|
||||
|
||||
Add `AptabaseProvider` to your RootLayout component:
|
||||
|
||||
```tsx
|
||||
import { AptabaseProvider } from '@aptabase/react';
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<AptabaseProvider appKey="<YOUR_APP_KEY>">{children}</AptabaseProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Setup for Next.js (Pages Router)</summary>
|
||||
|
||||
Add `AptabaseProvider` to your `_app` component:
|
||||
|
||||
```tsx
|
||||
import { AptabaseProvider } from '@aptabase/react';
|
||||
import type { AppProps } from 'next/app';
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
return (
|
||||
<AptabaseProvider appKey="<YOUR_APP_KEY>">
|
||||
<Component {...pageProps} />
|
||||
</AptabaseProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Setup for Remix</summary>
|
||||
|
||||
Add `AptabaseProvider` to your `entry.client.tsx` file:
|
||||
|
||||
```tsx
|
||||
import { AptabaseProvider } from '@aptabase/react';
|
||||
import { RemixBrowser } from '@remix-run/react';
|
||||
import { startTransition, StrictMode } from 'react';
|
||||
import { hydrateRoot } from 'react-dom/client';
|
||||
|
||||
startTransition(() => {
|
||||
hydrateRoot(
|
||||
document,
|
||||
<StrictMode>
|
||||
<AptabaseProvider appKey="<YOUR_APP_KEY>">
|
||||
<RemixBrowser />
|
||||
</AptabaseProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Setup for Create React App or Vite</summary>
|
||||
|
||||
Add `AptabaseProvider` to your root component:
|
||||
|
||||
```tsx
|
||||
import { AptabaseProvider } from '@aptabase/react';
|
||||
|
||||
ReactDOM.createRoot(root).render(
|
||||
<React.StrictMode>
|
||||
<AptabaseProvider appKey="<YOUR_APP_KEY>">
|
||||
<YourApp />
|
||||
</AptabaseProvider>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Advanced setup
|
||||
|
||||
The `AptabaseProvider` also supports an optional second parameter, which is an object with the `appVersion` property.
|
||||
|
||||
It's up to you to decide how to get the version of your app, but it's generally recommended to use your bundler (like Webpack, Vite, Rollup, etc.) to inject the values at build time. Alternatively you can also pass it in manually.
|
||||
|
||||
It's up to you to decide what to get the version of your app, but it's generally recommended to use your bundler (like Webpack, Vite, Rollup, etc.) to inject the values at build time.
|
||||
|
||||
## Tracking Events with Aptabase
|
||||
|
||||
After setting up the `AptabaseProvider`, you can then start tracking events using the `useAptabase` hook.
|
||||
|
||||
Here's an example of a simple counter component that tracks the `increment` and `decrement` events:
|
||||
|
||||
```js
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useAptabase } from '@aptabase/react';
|
||||
|
||||
export function Counter() {
|
||||
const { trackEvent } = useAptabase();
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
function increment() {
|
||||
setCount((c) => c + 1);
|
||||
trackEvent('increment', { count });
|
||||
}
|
||||
|
||||
function decrement() {
|
||||
setCount((c) => c - 1);
|
||||
trackEvent('decrement', { count });
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Count: {count}</p>
|
||||
<button onClick={increment}>Increment</button>
|
||||
<button onClick={decrement}>Decrement</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
A few important notes:
|
||||
|
||||
1. The SDK will automatically enhance the event with some useful information, like the OS and other properties.
|
||||
2. You're in control of what gets sent to Aptabase. This SDK does not automatically track any events, you need to call `trackEvent` manually.
|
||||
- Because of this, it's generally recommended to at least track an event at startup
|
||||
3. You do not need to await the `trackEvent` function, it'll run in the background.
|
||||
4. Only strings and numeric values are allowed on custom properties
|
||||
42
packages/react/package.json
Normal file
42
packages/react/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@aptabase/react",
|
||||
"version": "0.4.0",
|
||||
"type": "module",
|
||||
"description": "React SDK for Aptabase: Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"require": "./dist/index.cjs",
|
||||
"import": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/aptabase/aptabase-js.git",
|
||||
"directory": "packages/react"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/aptabase/aptabase-js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/aptabase/aptabase-js",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"files": [
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"dist",
|
||||
"package.json"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"react": "^18.0.0 || ^19.0.0"
|
||||
}
|
||||
}
|
||||
104
packages/react/src/index.tsx
Normal file
104
packages/react/src/index.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { getApiUrl, inMemorySessionId, sendEvent, validateAppKey, type AptabaseOptions } from '../../shared';
|
||||
|
||||
// Session expires after 1 hour of inactivity
|
||||
const SESSION_TIMEOUT = 1 * 60 * 60;
|
||||
const sdkVersion = `aptabase-react@${process.env.PKG_VERSION}`;
|
||||
|
||||
let _appKey = '';
|
||||
let _apiUrl: string | undefined;
|
||||
let _options: AptabaseOptions | undefined;
|
||||
let _eventsBeforeInit: { [key: string]: Record<string, string | number | boolean> | undefined } = {};
|
||||
|
||||
type ContextProps = {
|
||||
appKey?: string;
|
||||
options?: AptabaseOptions;
|
||||
isInitialized: boolean;
|
||||
};
|
||||
|
||||
function init(appKey: string, options?: AptabaseOptions) {
|
||||
if (!validateAppKey(appKey)) return;
|
||||
|
||||
_apiUrl = options?.apiUrl ?? getApiUrl(appKey, options);
|
||||
_appKey = appKey;
|
||||
_options = options;
|
||||
|
||||
Object.keys(_eventsBeforeInit).forEach((eventName) => {
|
||||
trackEvent(eventName, _eventsBeforeInit[eventName]);
|
||||
});
|
||||
_eventsBeforeInit = {};
|
||||
}
|
||||
|
||||
async function trackEvent(eventName: string, props?: Record<string, string | number | boolean>): Promise<void> {
|
||||
if (!_apiUrl) return;
|
||||
|
||||
const sessionId = inMemorySessionId(SESSION_TIMEOUT);
|
||||
|
||||
await sendEvent({
|
||||
apiUrl: _apiUrl,
|
||||
sessionId,
|
||||
appKey: _appKey,
|
||||
isDebug: _options?.isDebug,
|
||||
appVersion: _options?.appVersion,
|
||||
sdkVersion,
|
||||
eventName,
|
||||
props,
|
||||
});
|
||||
}
|
||||
|
||||
function trackEventBeforeInit(eventName: string, props?: Record<string, string | number | boolean>): Promise<void> {
|
||||
_eventsBeforeInit[eventName] = props;
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const AptabaseContext = createContext<ContextProps>({ isInitialized: false });
|
||||
|
||||
type Props = {
|
||||
appKey: string;
|
||||
options?: AptabaseOptions;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export { type AptabaseOptions };
|
||||
|
||||
export type AptabaseClient = {
|
||||
trackEvent: typeof trackEvent;
|
||||
};
|
||||
|
||||
export function AptabaseProvider({ appKey, options, children }: Props) {
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
init(appKey, options);
|
||||
setIsInitialized(true);
|
||||
}, [appKey, options]);
|
||||
|
||||
return <AptabaseContext.Provider value={{ appKey, options, isInitialized }}>{children}</AptabaseContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAptabase(): AptabaseClient {
|
||||
const ctx = useContext(AptabaseContext);
|
||||
|
||||
if (!ctx.appKey) {
|
||||
return {
|
||||
trackEvent: () => {
|
||||
console.warn(
|
||||
`Aptabase: useAptabase must be used within AptabaseProvider. Did you forget to wrap your app in <AptabaseProvider>?`,
|
||||
);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!ctx.isInitialized) {
|
||||
return {
|
||||
trackEvent: trackEventBeforeInit,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
trackEvent,
|
||||
};
|
||||
}
|
||||
15
packages/react/tsconfig.json
Normal file
15
packages/react/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es6",
|
||||
"strict": true,
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"jsx": "react-jsx",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"types": ["@types"]
|
||||
},
|
||||
"declaration": true,
|
||||
"declarationDir": "./dist"
|
||||
}
|
||||
}
|
||||
15
packages/react/tsup.config.ts
Normal file
15
packages/react/tsup.config.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'tsup';
|
||||
const { version } = require('./package.json');
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.tsx'],
|
||||
format: ['cjs', 'esm'],
|
||||
dts: true,
|
||||
splitting: false,
|
||||
minify: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
env: {
|
||||
PKG_VERSION: version,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user