NPM SDK
Official Faurya analytics SDK for web and React Native, with recommended CLI init flow and full runtime configuration.
Faurya NPM SDK
Official Faurya analytics SDK for web and React Native.
Start Here (Recommended)
Install once, run init once, and you are ready.
npm install faurya
npx faurya initExample
sahilgouri@sahils-MacBook-Pro fauryanpmtest % npx faurya init
Add Faurya server API helpers for goals and payments? (y/N): y
Faurya server API helpers will be added.
✅ Faurya setup completed
Framework detected: Next.js App Router
Files updated:
- .env.local
- .env.local
- lib/faurya.ts
- components/FauryaAnalytics.tsx
- lib/faurya-api.ts
- faurya.md
See usage guide: faurya.md
Next step:
Add your Faurya values:
FAURYA_SITE_ID=your-site-id
FAURYA_DOMAIN=your-domain.com
Then restart your dev server.That is the main setup flow.
After init, add your env values and restart your dev server:
FAURYA_SITE_ID=your-site-id
FAURYA_DOMAIN=your-domain.comWhat You Get When You Choose y For Server API Helpers
If you answer y to Add Faurya server API helpers for goals and payments, init creates lib/faurya-api.ts with helper functions you can call from your server routes and backend logic.
1) createFauryaGoal
Function call shape:
createFauryaGoal(fauryaVisitorId, name, metadata?)
Inputs:
fauryaVisitorId(string, required)name(string, required)metadata(object of string key-value pairs, optional)
Example calls:
import { createFauryaGoal } from "./lib/faurya-api";
await createFauryaGoal("visitor_123", "signup");
await createFauryaGoal("visitor_123", "book_demo", {
source: "pricing_page",
campaign: "spring_launch",
});2) createFauryaPayment
Function call shape:
createFauryaPayment(amount, currency, transactionId, options?)
Inputs:
amount(number, required)currency(string, required)transactionId(string, required)options(object, optional)
Optional options fields:
fauryaVisitorIdemailnamecustomerIdrenewalrefundedtimestamp
Example calls:
import { createFauryaPayment } from "./lib/faurya-api";
await createFauryaPayment(49, "USD", "txn_001");
await createFauryaPayment(99, "USD", "txn_002", {
fauryaVisitorId: "visitor_123",
email: "user@example.com",
customerId: "cus_789",
renewal: false,
refunded: false,
timestamp: new Date().toISOString(),
});3) trackFauryaEvent (Client Helper)
This helper is generated in lib/faurya.ts and is the standard client-side event call.
Function call shape:
trackFauryaEvent(eventName, metadata?)
Inputs:
eventName(string, required)metadata(object, optional)
Example calls:
import { trackFauryaEvent } from "./lib/faurya";
trackFauryaEvent("signup");
trackFauryaEvent("initiate_checkout", {
product_id: "prod_123",
plan_type: "pro",
currency: "USD",
});Why Use npx faurya init
faurya init is the fastest and safest way to set up Faurya because it scaffolds the integration for you.
It automatically:
- Detects your framework.
- Creates or updates env keys.
- Generates browser init helper files.
- Injects initialization into your app entry when safe.
- Prints a setup summary and next steps.
Supported framework detection:
- Next.js App Router (app/layout.tsx or src/app/layout.tsx)
- Next.js Pages Router (pages/_app.tsx or src/pages/_app.tsx)
- Vite React (vite.config.ts|js and src/main.tsx|jsx)
- Unknown framework fallback (safe no-crash mode)
Basic Usage After Init
Use the generated helper in your app code:
import { trackFauryaEvent } from "./lib/faurya";
trackFauryaEvent("signup");
trackFauryaEvent("initiate_checkout", {
product_id: "prod_123",
plan_type: "pro",
currency: "USD",
});Browser global shortcut (available after init):
window.faurya?.("signup");
window.faurya?.("initiate_checkout", { product_id: "prod_123" });Existing Basic SDK Code (Manual Style)
If you prefer direct SDK usage instead of generated helpers, this still works:
import { initFaurya } from "faurya";
// or: import { initFaurya } from "faurya/web"
const faurya = await initFaurya({
websiteId: "your-website-id",
domain: "your-domain.com",
});
faurya.track("button_click", { buttonId: "signup" });
faurya.trackGoal("signup", { source: "pricing_page" });
faurya.trackPageview("/pricing");
faurya.identify("user-42", { plan: "pro" });
await faurya.flush();
faurya.reset();track(goal_name, metadata) queues a custom event and sets extraData.eventName to your goal name.
Full initFaurya(...) Configuration (Direct SDK)
Use this when you want complete control instead of generated defaults:
await initFaurya({
// Required
websiteId: "your-site-id",
// Strongly recommended to always pass explicitly
domain: "your-domain.com",
// Optional endpoint override
apiUrl: "https://api.faurya.com",
// Privacy and identity mode
cookieless: false,
onCookielessVisitorId: (visitorId) => {
console.log("Cookieless visitor id:", visitorId);
},
// Logging and diagnostics
debug: false,
enableCliDebug: false,
// Queue behavior
flushInterval: 5000,
maxQueueSize: 20,
// Pageview behavior
autoCapturePageviews: {
enabled: true,
captureInitialPageview: true,
trackHashChanges: true,
debounceMs: 300,
},
// Runtime guards
allowLocalhost: false,
allowIframe: false,
// Cross-domain tracking allowlist
allowedHostnames: ["www.example.com", "app.example.com"],
// Browser feature toggles
enableAttentionTracking: true,
enablePageviewEnd: true,
autoDetectPayments: true,
enableGoalTracking: true,
});What each option means:
- websiteId: required project/site identifier in Faurya.
- domain: tracking domain for your site. Pass it explicitly to avoid local/IP hostname edge cases and keep data routing consistent.
- apiUrl: override API base URL (for custom or self-hosted endpoints).
- cookieless: disables cookie-based identity flow.
- onCookielessVisitorId: callback fired when cookieless visitor ID is resolved.
- debug: enables internal SDK debug logs.
- enableCliDebug: prints reasons when events are intentionally ignored by runtime guards.
- flushInterval: auto-flush interval in milliseconds.
- maxQueueSize: flushes immediately once queue reaches this size.
- autoCapturePageviews: enables, disables, and customizes automatic pageview tracking.
- allowLocalhost: allows tracking on localhost and local hostnames.
- allowIframe: allows tracking from iframe contexts.
- allowedHostnames: enable cross-domain ID transfer only for these hostnames.
- enableAttentionTracking: emits attention events based on visibility, focus, and idle state.
- enablePageviewEnd: emits page exit summary events.
- autoDetectPayments: auto-detects payment completions from supported URL params.
- enableGoalTracking: enables [data-faurya-goal] auto goal capture.
Full faurya init Configuration
Command
npx faurya initCLI options
- --with-api (alias: --api): also scaffold server API helpers for goals and payments.
- --no-api: skip server API helper scaffolding.
- No option: interactive prompt asks whether to add server API helpers.
Env keys used by init
Always used:
- FAURYA_SITE_ID
- FAURYA_DOMAIN
Only when server API helpers are enabled:
- FAURYA_API_KEY
Env file behavior
- Next.js: updates .env.local and can reuse fallback values from .env.
- Vite or Unknown: updates .env.
- Existing non-empty values are preserved (never overwritten).
- Missing keys are appended.
Client env exposure updates
Next.js (next.config.js or next.config.ts):
env: {
FAURYA_SITE_ID: process.env.FAURYA_SITE_ID,
FAURYA_DOMAIN: process.env.FAURYA_DOMAIN,
}Vite (vite.config.ts or vite.config.js):
envPrefix: ["VITE_", "FAURYA_"];Files that faurya init creates or updates
Depending on framework and project structure:
- src/lib/faurya.ts (or lib/faurya.ts if no src/)
- .env.local (Next.js) or .env (Vite or Unknown)
- next.config.js or next.config.ts (Next.js)
- vite.config.ts or vite.config.js (Vite)
- src/components/FauryaAnalytics.tsx (or components/FauryaAnalytics.tsx) for Next.js
- Entry-point injection (app/layout.tsx, pages/_app.tsx, or src/main.tsx|jsx)
- faurya.md usage guide
- Optional src/lib/faurya-api.ts (or lib/faurya-api.ts) when --with-api or --api is enabled
Optional server API helpers
When enabled, init scaffolds server-side helpers to call Faurya API endpoints:
- createFauryaGoal(...)
- createFauryaPayment(...)
These helpers require FAURYA_API_KEY in server env.
Runtime Notes
- Browser-first SDK.
- SSR and server-only runtime no-ops browser client methods safely.
- Browser-only captures (pageview, pageview_end, attention, data-faurya-goal, data-faurya-scroll) run only in eligible browser environments.
- In cookieless: true, cookie-based ID storage and cross-domain URL param usage are disabled.
Subpath Exports
| Import Path | Description |
|---|---|
| faurya | Main web SDK and core utilities |
| faurya/web | Web-only export surface |
| faurya/react-native | React Native provider and hooks |
Terminal Errors and Warnings (Meaning of Each)
Below are terminal-facing messages users may see from CLI setup or generated helpers.
| Message | Meaning | What to do |
|---|---|---|
| Unknown command: <command> | The CLI command is invalid. | Run npx faurya init. |
| [Faurya] <error message> | The CLI failed with an unexpected runtime error. | Read the message, fix the referenced file/env/path issue, then run again. |
| [Faurya] Missing FAURYA_SITE_ID. Add it to your env file. | Browser init helper ran without FAURYA_SITE_ID. | Add FAURYA_SITE_ID to env and restart dev server. |
| [Faurya] Missing FAURYA_API_KEY. Add it to your server env file. | Server API helper was used without API key. | Add FAURYA_API_KEY in server env only (never expose client-side). |
| Could not safely update <next-config>. Add env.FAURYA_SITE_ID and env.FAURYA_DOMAIN manually. | CLI could not safely patch your Next config shape. | Manually add those env mappings in Next config. |
| Could not safely update <vite-config>. Add envPrefix: ['VITE_', 'FAURYA_'] manually. | CLI could not safely patch your Vite config shape. | Manually add envPrefix: ['VITE_', 'FAURYA_']. |
| <file> already exists and was not overwritten... | CLI found an existing file and skipped overwrite for safety. | Keep your file or manually align required exports. |
| Could not find </body> in <layout>. Add <FauryaAnalytics /> manually inside <body>. | Next App Router layout injection point was not found. | Add <FauryaAnalytics /> manually inside <body>. |
| Could not find <Component /> in <_app>. Add <FauryaAnalytics /> manually. | Next Pages Router _app injection point was not found. | Add <FauryaAnalytics /> manually in _app. |
| Could not determine where to initialize Faurya in <main-file>. | Vite entry file shape is non-standard, so auto-init location was unclear. | Import and call initFauryaClient() manually near app bootstrap. |
Ignored Event Reasons (enableCliDebug)
When enableCliDebug: true, you may see these reason codes:
- disabled_no_window: non-browser runtime (SSR or backend or API routes)
- disabled_file_protocol: running from file://
- disabled_localhost: localhost blocked unless allowLocalhost: true
- disabled_iframe: iframe blocked unless allowIframe: true
- disabled_bot: bot or headless or webdriver detected
Contact
For support and integration help: team@faurya.com
License
MIT