# Next.js Configuration (/docs/configuration)
Next.js Configuration [#nextjs-configuration]
The Journium Next.js SDK extends the [React SDK](/docs/react) with Next.js-specific optimizations including automatic route change tracking for both App Router and Pages Router.
Next.js-Specific Setup [#nextjs-specific-setup]
Provider Configuration [#provider-configuration]
```tsx title="app/layout.tsx"
import { NextJourniumProvider } from '@journium/nextjs';
const journiumConfig = {
publishableKey: process.env.NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY!,
options: {
debug: process.env.NODE_ENV === 'development',
autoTrackPageviews: true, // Auto-tracks route changes
autocapture: true
}
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
```
```tsx title="pages/_app.tsx"
import type { AppProps } from 'next/app';
import { NextJourniumProvider } from '@journium/nextjs';
const journiumConfig = {
publishableKey: process.env.NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY!,
options: {
debug: process.env.NODE_ENV === 'development',
autoTrackPageviews: true, // Auto-tracks route changes
autocapture: true
}
};
export default function App({ Component, pageProps }: AppProps) {
return (
);
}
```
Configuration Options [#configuration-options]
The `config` prop accepts a `JourniumConfig` object with the same options as the JavaScript SDK.
For detailed information about all available configuration options, see the [JavaScript SDK Configuration Guide](/docs/js/configuration).
**Next.js-specific considerations:**
* `autoTrackPageviews` - Set to `true` to automatically track Next.js route changes (recommended)
* Environment variables should use `NEXT_PUBLIC_` prefix for client-side access
* Configuration is SSR-compatible
Next.js Components [#nextjs-components]
[#nextjourniumprovider]
Provider component with Next.js optimizations and automatic route tracking.
**Props:**
| Prop | Type | Required | Description |
| ----------------------- | ---------------------- | -------- | ---------------------- |
| `config` | `JourniumConfig` | Yes | Configuration object |
| `config.publishableKey` | `string` | Yes | Your publishable key |
| `config.apiHost` | `string` | No | Custom API endpoint |
| `config.options` | `JourniumLocalOptions` | No | Configuration options |
| `children` | `ReactNode` | Yes | React children to wrap |
**Next.js Features:**
* ✅ Automatic route change detection (App Router and Pages Router)
* ✅ SSR-compatible initialization
* ✅ Works with `next/navigation` and `next/router`
* ✅ Optimized for serverless deployments
Automatic Route Tracking [#automatic-route-tracking]
The Next.js provider automatically tracks route changes in both App Router and Pages Router:
```tsx
// Automatically tracked:
router.push('/products/123');
router.replace('/checkout');
About
```
**Disable automatic tracking:**
```tsx
```
Then manually track pageviews:
```tsx
'use client';
import { useTrackPageview } from '@journium/nextjs';
import { usePathname } from 'next/navigation';
import { useEffect } from 'react';
export function PageTracker() {
const pathname = usePathname();
const trackPageview = useTrackPageview();
useEffect(() => {
trackPageview({ pathname });
}, [pathname, trackPageview]);
return null;
}
```
React Hooks [#react-hooks]
The Next.js SDK includes all React hooks. See the [React Hooks documentation](/docs/react/hooks) for details:
* `useTrackEvent()` - Track custom events
* `useIdentify()` - Identify users
* `useReset()` - Reset user identity
* `useTrackPageview()` - Manual pageview tracking
* `useAutoTrackPageview()` - Automatic pageview tracking
* `useAutocapture()` - Control autocapture
* `useJournium()` - Access analytics instance
Server-Side Rendering (SSR) [#server-side-rendering-ssr]
The SDK is SSR-compatible and will not cause hydration issues:
```tsx
// ✅ Safe in Next.js
export default function Layout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
The analytics instance is only initialized on the client side.
Environment Variables [#environment-variables]
App Router / Pages Router [#app-router--pages-router]
```bash title=".env.local"
NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY=pk_your_key_here
```
```tsx
const config = {
publishableKey: process.env.NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY!
};
```
Different Keys per Environment [#different-keys-per-environment]
```bash title=".env.local"
# Development
NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY=pk_test_...
# .env.production
NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY=pk_live_...
```
TypeScript Support [#typescript-support]
The Next.js SDK is fully typed with the same types as the JavaScript SDK.
For complete type definitions, see the [JavaScript SDK TypeScript Types](/docs/js/typescript-types) documentation.
```typescript
import {
type JourniumConfig,
type JourniumLocalOptions,
type AutocaptureOptions
} from '@journium/nextjs';
```
API Reference [#api-reference]
For detailed API method reference, see the [JavaScript SDK API Methods](/docs/js/api-methods).
The Next.js SDK provides the same methods through React hooks:
| Hook | Underlying Method | Documentation |
| ----------------- | ---------------------- | ---------------------------------------- |
| `useTrackEvent()` | `analytics.track()` | [API Ref](/docs/js/api-methods#track) |
| `useIdentify()` | `analytics.identify()` | [API Ref](/docs/js/api-methods#identify) |
| `useReset()` | `analytics.reset()` | [API Ref](/docs/js/api-methods#reset) |
Deployment Considerations [#deployment-considerations]
Vercel [#vercel]
Works out of the box. Environment variables are automatically available with `NEXT_PUBLIC_` prefix.
Self-Hosted [#self-hosted]
Ensure environment variables are configured:
```bash title=".env.production"
NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY=pk_live_...
```
Then build normally:
```bash
npm run build
```
Next Steps [#next-steps]
Learn about all available hooks for Next.js
See all configuration options in detail
Complete API method reference
# How Journium Works (/docs/how-journium-works)
Journium works by collecting [Events](/docs/concepts/events) from your application and then using AI to generate insights
from those events. Users integrate the Journium SDK into their applications, which sends events
to Journium's API where they are ingested and processed. Users then create [Insight Trackers](/docs/concepts/insight-trackers) that define
the mechanics around how [Insights](/docs/concepts/insights) should be generated, and [Jobs](/docs/concepts/jobs)
execute those trackers to produce insights. These insights are then available on the Journium dashboard for users to view and analyze.
Journium Workflow [#journium-workflow]
The diagram below illustrates the complete Journium workflow:
Event Collection [#event-collection]
Event collection is the foundation of Journium's analytics pipeline. Users integrate
the Journium SDK into their applications, which acts as a lightweight client library
that captures user interactions and application events. When events occur in your
application—such as user signups, purchases, feature usage, or errors—the SDK automatically
sends these events to Journium's API endpoint. The API receives and ingests these events,
storing them in a time-series database optimized for analytics queries. This continuous
stream of event data provides the raw material that powers all subsequent analysis
and insight generation.
Tracker Definition [#tracker-definition]
Trackers are declarative configurations that define what should be analyzed and how insights
should be generated. Users create trackers through the Journium dashboard, specifying
which events to monitor (or analyzing all events), setting custom instructions for
the AI analysis, and configuring execution schedules. Each tracker acts like a continuous
data analyst that monitors specific patterns in your event data. Trackers can be set to
run automatically on a schedule (e.g., hourly, daily, weekly) or triggered manually
for ad-hoc analysis. The tracker configuration includes parameters such as the maximum number
of events to analyze, custom AI instructions that guide the analysis focus, and the
specific event types to consider. This "Insights as Code" approach allows users to define
what they want to know about their application without writing SQL queries or building dashboards.
Job Execution [#job-execution]
Job execution is the automated process that runs trackers and generates insights. When a tracker
is scheduled to run or manually triggered, Journium creates a job that executes the tracker's
analysis workflow. The job execution follows a multi-step pipeline: it first validates the
tracker configuration and checks data availability, then queries the event database to
retrieve the relevant events based on the tracker's configuration. The job then uses AI
to analyze the event data, looking for patterns, trends, anomalies, and correlations. The
AI engine processes the data according to the tracker's instructions, synthesizing findings
into concise, natural language insights that are typically 1-3 sentences long and backed
by verifiable data. Finally, the job stores the generated insights and updates the execution
history, making them ready for display in the dashboard.
Insights Display [#insights-display]
Once insights are generated by job execution, they become available in the Journium dashboard
for users to view and analyze. Insights are displayed in a feed format on the application instance's
insights page, similar to a social media feed, where each insight appears as a card showing the
analysis results, timestamp, and metadata. Users can interact with insights by liking them, adding
comments for team collaboration, saving them for later reference, or sharing them with team members.
The dashboard also provides features like pagination to browse through historical insights,
filtering options, and the ability to see insight trends over time. This presentation format makes
insights easily scannable and actionable, transforming raw event data into understandable narratives
that help teams make data-driven decisions about their application.
# Journium Docs (/docs)
import { NextJsIcon } from '@/components/icons/nextjs';
import { ReactIcon } from '@/components/icons/react';
import { AngularIcon } from '@/components/icons/angular';
import { JsIcon } from '@/components/icons/js';
Journium turns raw telemetry into proactive, narrative insights — without charts, queries, or BI.
Find the right guide for your needs, whether you are just getting stated or looking to implement advanced features.
} href="/docs/quick-start">
Get started with Journium in your Next.js application
} href="/docs/react">
Integrate Journium into your React application
} href="/docs/angular">
Add Journium tracking to your Angular application
} href="/docs/js">
Add Journium tracking to your vanilla JavaScript application
# Next.js Quick Start (/docs/quick-start)
Setup [#setup]
Set up Journium for your Next.js application.
Install @journium/nextjs [#install-journiumnextjs]
The [Journium Next.js SDK](/docs/hooks) gives you access to pre-built hooks and components to help you generate events
in your Next.js application and get insights from your data.
Run the following command to install the SDK:
npm
pnpm
yarn
bun
```bash title="Terminal"
npm i @journium/nextjs
```
```bash title="Terminal"
pnpm add @journium/nextjs
```
```bash title="Terminal"
yarn add @journium/nextjs
```
```bash title="Terminal"
bun add @journium/nextjs
```
Set your Journium Publishable Key [#set-your-journium-publishable-key]
1. **Sign up for a Journium account** for free at [journium.app/signup](https://journium.app/signup)
2. **[Create an application](https://dashboard.journium.app/apps/new)** in your Journium dashboard
3. **Copy your Publishable Key** from the [Developers | API Keys](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/api-keys) section
Dashboard URLs automatically navigate to your app - just click!
4. **Create a `.env.local` file** in your project root:
```bash
touch .env.local
```
5. **Add your key** to the `.env.local` file:
```bash title=".env.local"
NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY=your_publishable_key_here
```
6. **Verify your setup** - check that the key is correctly saved:
```bash
cat .env.local
# Should show: NEXT_PUBLIC_JOURNIUM_PUBLISHABLE_KEY=pk_test_...
```
Development instances use `pk_test_` keys. Production keys start with `pk_live_`.
Add to your app [#add-nextjourniumprovider-to-your-app]
The `` component provides session and user context to Journium's hooks.
It's recommended to wrap your entire app at the entry point with ``
to make analytics globally accessible throughout your application.
```tsx title="app/layout.tsx"
// [!code ++:1]
import { NextJourniumProvider } from '@journium/nextjs';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{/* [!code ++:1] */}
{children}
{/* [!code ++:1] */}
);
}
```
```tsx title="pages/_app.tsx"
import type { AppProps } from 'next/app';
// [!code ++:1]
import { NextJourniumProvider } from '@journium/nextjs';
export default function App({ Component, pageProps }: AppProps) {
return (
{/* [!code ++:1] */}
{/* [!code ++:1] */}
);
}
```
Run the Development Server [#run-the-development-server]
Start your application:
npm
pnpm
yarn
bun
```bash title="Terminal"
npm run dev
```
```bash title="Terminal"
pnpm run dev
```
```bash title="Terminal"
yarn dev
```
```bash title="Terminal"
bun run dev
```
**Using a custom port?** Next.js defaults to port 3000. To use a different port, set the `PORT` environment variable or use `-p` flag: `npm run dev -- -p 3001`
Verify Your Setup [#verify-your-setup]
Open [http://localhost:3000](http://localhost:3000) (or your custom port) in your browser to see the application running.
Send Events to Journium [#send-events-to-journium]
Navigate around your app to automatically send events to Journium.
Then view your collected events at [Developers | Events](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/events).
**Success indicator:** You should see events appearing in your dashboard within a few seconds.
Generate Your First Insight [#generate-your-first-insight]
When you create an app in Journium, a default [Insight Tracker](/docs/concepts/insight_trackers) is automatically created. This tracker helps you test data ingestion and insight generation.
1. Go to your [Developers | Insight Trackers](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/insight-trackers) page
2. Click the **`Analyze now`** button for the tracker titled **"User Engagement"**
3. Monitor the job status in [Developers | Jobs](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/jobs)
4. Wait for the job to complete (usually takes 1-2 minutes)
5. View your generated insights at [Dashboard | Insights](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/insights)
Done [#done]
**Congratulations!** You've successfully created your first insight with Journium!
Troubleshooting [#troubleshooting]
* Verify your API key starts with `pk_` and is correctly set in `.env.local`
* Check browser console for errors (F12 → Console)
* Ensure you're interacting with your **local app** (not the dashboard)
* Restart the dev server after changing `.env.local` file
* Delete `node_modules` and reinstall dependencies:
```bash
rm -rf node_modules && npm install
```
* Ensure Node.js version is 18+:
```bash
node --version
```
* Use a different port:
```bash
npm run dev -- -p 3001
```
* Or stop the process using the port:
```bash
# macOS/Linux
lsof -ti:3000 | xargs kill -9
```
* Ensure the file is named exactly `.env.local` (not `.env.local.txt`)
* Restart the development server after creating/modifying `.env.local`
* Check file location: it must be in the project root, not in `app/` or `pages/`
* For Next.js, environment variables must be prefixed with `NEXT_PUBLIC_` to be accessible in the browser
What's next? [#whats-next]
Learn how to send your own custom events to track user behavior.
Create custom analytics and understand how insights are generated.
# What is Journium (/docs/what-is-journium)
import { RocketIcon } from 'lucide-react';
**Journium** turns raw telemetry into proactive, narrative insights — without charts, queries, or BI. Instead of asking humans to hunt through dashboards, Journium sits on top of your application's data and automatically detects meaningful behavioral changes, explains what happened, and surfaces insights in plain language.
**Data exists. Awareness doesn't.** Journium flips that model.
The Problem We're Solving [#the-problem-were-solving]
Modern applications generate mountains of event data — every click, page view, transaction, and user interaction creates a data point. Yet despite this abundance of information, organizations struggle to extract clear, actionable insights in a timely manner.
The Traditional Analytics Trap [#the-traditional-analytics-trap]
The conventional approach to analytics follows a broken pattern:
**Telemetry → Storage → Queries → Dashboards → Hope**
Teams collect data, store it, build dashboards, and then... hope someone notices something important. This process demands:
* **Manual exploration** — analysts must preprocess data, run queries, and interpret results
* **Domain expertise** — understanding what to look for requires deep knowledge
* **Significant time** — valuable knowledge often remains buried because generating insights traditionally requires significant manual effort
* **Reactive discovery** — by the time an insight is found, it may be too late to act
The result? **We have a data overload, but an insights shortage.** Busy product teams and executives rarely have the luxury to sift through dashboards or craft SQL queries on the fly. Important findings may be discovered too late or not at all.
Why Dashboards Fall Short [#why-dashboards-fall-short]
Static dashboards can show you *what* happened, but they rarely explain *why*. Even specialized BI tools struggle to surface the root causes behind metric movements. You're left with charts that require interpretation, correlation analysis, and often, a bit of guesswork.
How Journium Flips the Narrative [#how-journium-flips-the-narrative]
Journium reimagines analytics from the ground up. Instead of passive reporting tools, we've built an active system that acts like a data analyst working 24/7.
The New Model: Telemetry → Meaning → Action [#the-new-model-telemetry--meaning--action]
Journium follows a simple, powerful principle:
**Telemetry → Meaning → Action**
Not: Telemetry → Storage → Queries → Dashboards → Hope
Your application doesn't need more dashboards. It needs a way to **speak up** when something meaningful changes.
From Passive to Proactive [#from-passive-to-proactive]
Traditional analytics asks: *"What do you want to know?"*\
Journium asks: *"What should you know?"*
Instead of waiting for someone to query the data, Journium continuously monitors your application's behavior, detects significant changes, performs root-cause analysis, and delivers concise insights directly to you — in Slack, email, or wherever you need them.
Think of it this way: Who has the time or interest to dig through charts if an AI can directly tell you *"users from segment X are churning due to feature Y issues, impacting conversion by Z%"* — with the data to back it up?
Insights as Code: The Foundation [#insights-as-code-the-foundation]
Journium introduces **"Insights as Code"** — a novel approach where insights are treated as a first-class, codified product, and an AI-driven engine transforms raw event data into human-ready insights.
What This Means [#what-this-means]
Just as Infrastructure as Code revolutionized how servers and networks are configured, Insights as Code brings software engineering rigor to analytics:
* **Declarative specifications** — Define what you care about in code or configuration, not spreadsheets or Wiki pages
* **Version-controlled** — Track changes, review insights, and maintain consistency across your team
* **Automated generation** — Let AI do the heavy lifting of data crunching, pattern finding, and explanation generation
* **Verifiable and transparent** — Every insight is backed by code and data, making it transparent and trustworthy
The Power of AI-Driven Analysis [#the-power-of-ai-driven-analysis]
Journium leverages Generative AI and large language models to automate insight generation. But this isn't about dumping data into an LLM and hoping for the best. Instead, we use a sophisticated, multi-step approach:
1. **Continuous monitoring** — Track behavioral patterns and detect significant changes
2. **Intelligent analysis** — Use AI agents to pose analytical questions, break them into sub-questions, query data, and synthesize findings
3. **Validation and guardrails** — Ensure insights are both interesting and trustworthy, with automatic validation of claims
4. **Concise delivery** — Generate short, factual takeaways (not long-winded reports) that get straight to the point
This approach ensures insights are **concise, factual takeaways** rather than shallow observations or obvious outliers.
The Vision: An Always-On System [#the-vision-an-always-on-system]
Journium transforms analytics from a reactive process into an **always-on system** that actively drives growth. The vision is simple:
1. **Instrument once** — Integrate Journium's SDK into your application
2. **Define what matters** — Specify your goals and questions in configuration
3. **Receive insights automatically** — Get proactive, narrative insights delivered continuously
The outcome? An analytics experience that feels almost magical: you integrate an SDK, define high-level goals in a config, and the system speaks to you with facts and explanations continuously — almost like a data-savvy colleague working around the clock.
Yet under the hood, every insight is backed by code and data — transparent and verifiable.
Why This Matters [#why-this-matters]
In a world inundated with data, those who can harness AI to tell the story of the data will leap ahead. Journium eliminates the traditional divide between "data collection" and "insight generation," drastically reducing the time from question to answer and empowering teams to be truly data-driven without slogging through dashboards.
The barrier to trying a new analysis becomes so low — just write a new tracker and let the AI do the rest. This unlocks creative uses of analytics that were previously too time-consuming or resource-intensive to pursue.
**Stop looking for insights. Let your application tell you.**
} href="/docs" horizontal="true">
Get Journium integrated into your app in under 5 minutes
# Angular Configuration (/docs/angular/configuration)
Angular Configuration [#angular-configuration]
The Journium Angular SDK wraps the core [JavaScript SDK](/docs/js) and provides Angular-specific service and providers.
Angular Version Compatibility [#angular-version-compatibility]
`@journium/angular` requires **Angular 15 or later**. All APIs used (`makeEnvironmentProviders`, `inject()`, `APP_INITIALIZER`) have been stable since Angular 15.
| Angular | Standalone API | NgModule API | Signals | Zoneless |
| ------- | -------------- | ------------ | ------- | ---------------- |
| 15 | ✅ | ✅ | — | — |
| 16 | ✅ | ✅ | — | — |
| 17 | ✅ | ✅ | ✅ | — |
| 18 | ✅ | ✅ | ✅ | ✅ (experimental) |
| 19 | ✅ | ✅ | ✅ | ✅ (experimental) |
| 20 / 21 | ✅ | ✅ | ✅ | ✅ (experimental) |
The SDK is **zone-agnostic**: no `NgZone`, no `ChangeDetectorRef` coupling. It works identically in zone.js, zoneless, and signal-based component trees.
Angular-Specific Setup [#angular-specific-setup]
Standalone App Configuration [#standalone-app-configuration]
Use `provideJournium()` in `bootstrapApplication`:
```typescript title="src/main.ts"
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideJournium, withJourniumRouter } from '@journium/angular';
import { environment } from './environments/environment';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideJournium({
publishableKey: environment.journiumPublishableKey,
options: {
debug: !environment.production,
autoTrackPageviews: true,
autocapture: true,
},
}),
provideRouter(routes),
withJourniumRouter(), // Auto-track pageviews on NavigationEnd
],
});
```
NgModule Configuration [#ngmodule-configuration]
Use `JourniumModule.forRoot()` in your root module:
```typescript title="src/app/app.module.ts"
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { JourniumModule } from '@journium/angular/ngmodule';
import { environment } from '../environments/environment';
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(routes),
JourniumModule.forRoot({
publishableKey: environment.journiumPublishableKey,
options: {
debug: !environment.production,
autoTrackPageviews: true,
autocapture: true,
},
}),
],
bootstrap: [AppComponent],
})
export class AppModule {}
```
Configuration Options [#configuration-options]
The `config` object passed to `provideJournium()` or `JourniumModule.forRoot()` accepts a `JourniumConfig` object:
* `publishableKey` (required): Your Journium publishable key
* `apiHost` (optional): Custom API endpoint
* `options` (optional): Configuration options object
For detailed information about all available configuration options, see the [JavaScript SDK Configuration Guide](/docs/js/configuration).
**Common options:**
* `debug` - Enable debug logging
* `flushAt` - Number of events before auto-flush
* `flushInterval` - Flush interval in milliseconds
* `sessionTimeout` - Session timeout duration
* `autoTrackPageviews` - Automatically track page views
* `autocapture` - Configure automatic event capture
Angular Providers [#angular-providers]
provideJournium(config) [#providejourniumconfig]
Returns `EnvironmentProviders` for use in `bootstrapApplication`. This is the recommended approach for standalone Angular 15+ apps.
```typescript
import { provideJournium } from '@journium/angular';
bootstrapApplication(AppComponent, {
providers: [
provideJournium({ publishableKey: 'pk_...' }),
],
});
```
withJourniumRouter() [#withjourniumrouter]
Optional router integration. Subscribes to Angular Router `NavigationEnd` events and automatically calls `capturePageview()` on each navigation.
```typescript
import { provideJournium, withJourniumRouter } from '@journium/angular';
import { provideRouter } from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [
provideJournium({ publishableKey: 'pk_...' }),
provideRouter(routes),
withJourniumRouter(), // Must come after provideRouter()
],
});
```
JourniumModule.forRoot(config) (NgModule pattern) [#journiummoduleforrootconfig-ngmodule-pattern]
For Angular apps using NgModule, import `JourniumModule.forRoot()` once in your root module. This provides `JourniumService` application-wide via Angular's DI.
JourniumService [#journiumservice]
Inject `JourniumService` in any component or service. See the [JourniumService reference](/docs/angular/services/journium-service) for available methods.
```typescript
import { JourniumService } from '@journium/angular';
@Component({ ... })
export class MyComponent {
constructor(private journium: JourniumService) {}
}
```
TypeScript Support [#typescript-support]
The Angular SDK is fully typed. All types are re-exported from `@journium/angular`:
```typescript
import {
type JourniumConfig,
type JourniumLocalOptions,
type AutocaptureOptions,
} from '@journium/angular';
```
Next Steps [#next-steps]
Learn about all JourniumService methods
See all configuration options in detail
Complete API method reference
# How Journium Works (/docs/angular/how-journium-works)
Journium works by collecting [Events](/docs/angular/concepts/events) from your application and then using AI to generate insights
from those events. Users integrate the Journium SDK into their applications, which sends events
to Journium's API where they are ingested and processed. Users then create [Insight Trackers](/docs/angular/concepts/insight-trackers) that define
the mechanics around how [Insights](/docs/angular/concepts/insights) should be generated, and [Jobs](/docs/angular/concepts/jobs)
execute those trackers to produce insights. These insights are then available on the Journium dashboard for users to view and analyze.
Journium Workflow [#journium-workflow]
Event Collection [#event-collection]
Event collection is the foundation of Journium's analytics pipeline. Users integrate
the Journium SDK into their applications, which acts as a lightweight client library
that captures user interactions and application events. When events occur in your
application—such as user signups, purchases, feature usage, or errors—the SDK automatically
sends these events to Journium's API endpoint. The API receives and ingests these events,
storing them in a time-series database optimized for analytics queries. This continuous
stream of event data provides the raw material that powers all subsequent analysis
and insight generation.
Tracker Definition [#tracker-definition]
Trackers are declarative configurations that define what should be analyzed and how insights
should be generated. Users create trackers through the Journium dashboard, specifying
which events to monitor (or analyzing all events), setting custom instructions for
the AI analysis, and configuring execution schedules. Each tracker acts like a continuous
data analyst that monitors specific patterns in your event data. Trackers can be set to
run automatically on a schedule (e.g., hourly, daily, weekly) or triggered manually
for ad-hoc analysis. The tracker configuration includes parameters such as the maximum number
of events to analyze, custom AI instructions that guide the analysis focus, and the
specific event types to consider. This "Insights as Code" approach allows users to define
what they want to know about their application without writing SQL queries or building dashboards.
Job Execution [#job-execution]
Job execution is the automated process that runs trackers and generates insights. When a tracker
is scheduled to run or manually triggered, Journium creates a job that executes the tracker's
analysis workflow. The job execution follows a multi-step pipeline: it first validates the
tracker configuration and checks data availability, then queries the event database to
retrieve the relevant events based on the tracker's configuration. The job then uses AI
to analyze the event data, looking for patterns, trends, anomalies, and correlations. The
AI engine processes the data according to the tracker's instructions, synthesizing findings
into concise, natural language insights that are typically 1-3 sentences long and backed
by verifiable data. Finally, the job stores the generated insights and updates the execution
history, making them ready for display in the dashboard.
Insights Display [#insights-display]
Once insights are generated by job execution, they become available in the Journium dashboard
for users to view and analyze. Insights are displayed in a feed format on the application instance's
insights page, similar to a social media feed, where each insight appears as a card showing the
analysis results, timestamp, and metadata. Users can interact with insights by liking them, adding
comments for team collaboration, saving them for later reference, or sharing them with team members.
The dashboard also provides features like pagination to browse through historical insights,
filtering options, and the ability to see insight trends over time. This presentation format makes
insights easily scannable and actionable, transforming raw event data into understandable narratives
that help teams make data-driven decisions about their application.
# Angular Quick Start (/docs/angular)
Setup [#setup]
Set up Journium for your Angular application.
Install @journium/angular [#install-journiumangular]
The [Journium Angular SDK](/docs/angular/services) gives you access to a `JourniumService`, Angular module, and provider functions to send events from your Angular application and get insights from your data.
Run the following command to install the SDK:
npm
pnpm
yarn
bun
```bash title="Terminal"
npm i @journium/angular
```
```bash title="Terminal"
pnpm add @journium/angular
```
```bash title="Terminal"
yarn add @journium/angular
```
```bash title="Terminal"
bun add @journium/angular
```
Set your Journium Publishable Key [#set-your-journium-publishable-key]
1. **Sign up for a Journium account** for free at [journium.app/signup](https://journium.app/signup)
2. **[Create an application](https://dashboard.journium.app/apps/new)** in your Journium dashboard
3. **Copy your Publishable Key** from the [Developers | API Keys](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/api-keys) section
Dashboard URLs automatically navigate to your app - just click!
4. **Add your key** to `src/environments/environment.ts`:
```typescript title="src/environments/environment.ts"
export const environment = {
production: false,
journiumPublishableKey: 'your_publishable_key_here',
};
```
Development instances use `pk_test_` keys. Production keys start with `pk_live_`.
Initialize Journium in your app [#initialize-journium-in-your-app]
The Journium Angular SDK supports both **standalone** (Angular 15+) and **NgModule** patterns.
Add `provideJournium()` to your `bootstrapApplication` call in `src/main.ts`:
```typescript title="src/main.ts"
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
// [!code ++:2]
import { provideJournium, withJourniumRouter } from '@journium/angular';
import { environment } from './environments/environment';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
// [!code ++:7]
provideJournium({
publishableKey: environment.journiumPublishableKey,
}),
provideRouter(routes),
// Optional: automatically track pageviews on each route change
withJourniumRouter(),
],
});
```
Import `JourniumModule.forRoot()` in your root `AppModule`:
```typescript title="src/app/app.module.ts"
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
// [!code ++:2]
import { JourniumModule } from '@journium/angular/ngmodule';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
// [!code ++:3]
JourniumModule.forRoot({
publishableKey: environment.journiumPublishableKey,
}),
],
bootstrap: [AppComponent],
})
export class AppModule {}
```
Use JourniumService in your components [#use-journiumservice-in-your-components]
Inject `JourniumService` to track events anywhere in your app:
```typescript title="src/app/pages/home.component.ts"
import { Component } from '@angular/core';
// [!code ++:1]
import { JourniumService } from '@journium/angular';
@Component({
selector: 'app-home',
standalone: true,
template: `
`,
})
export class HomeComponent {
// [!code ++:1]
constructor(private journium: JourniumService) {}
handleClick(): void {
// [!code ++:4]
this.journium.track('button_clicked', {
page: 'home',
button_text: 'Track Event',
});
}
}
```
Run the Development Server [#run-the-development-server]
Start your application:
```bash title="Terminal"
ng serve
```
**Using a custom port?** Pass `--port 4200` to the serve command. The default Angular port is `4200`.
Verify Your Setup [#verify-your-setup]
Open [http://localhost:4200](http://localhost:4200) in your browser. Interact with your app to generate events.
Send Events to Journium [#send-events-to-journium]
Navigate around your app to automatically send events to Journium.
Then view your collected events at [Developers | Events](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/events).
**Success indicator:** You should see events appearing in your dashboard within a few seconds.
Generate Your First Insight [#generate-your-first-insight]
When you create an app in Journium, a default [Insight Tracker](/docs/angular/concepts/insight_trackers) is automatically created. This tracker helps you test data ingestion and insight generation.
1. Go to your [Developers | Insight Trackers](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/insight-trackers) page
2. Click the **`Analyze now`** button for the tracker titled **"User Engagement"**
3. Monitor the job status in [Developers | Jobs](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/jobs)
4. Wait for the job to complete (usually takes 1-2 minutes)
5. View your generated insights at [Dashboard | Insights](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/insights)
Done [#done]
**Congratulations!** You've successfully created your first insight with Journium!
Troubleshooting [#troubleshooting]
* Verify your publishable key starts with `pk_` and is correctly set in `environment.ts`
* Check browser console for errors (F12 → Console)
* Ensure you're interacting with your **local app** (not the dashboard)
* Restart the dev server after changing `environment.ts`
* Delete `node_modules` and reinstall:
```bash
rm -rf node_modules && npm install
```
* Ensure Angular 15+ is installed:
```bash
ng version
```
* Verify `experimentalDecorators: true` is set in your `tsconfig.json`
* Ensure `provideJournium()` is called in `bootstrapApplication` (standalone) or `JourniumModule.forRoot()` is imported in `AppModule` (NgModule)
* `JourniumService` must be provided at the root level — not in a lazy-loaded module
* Ensure `withJourniumRouter()` is included in the providers array alongside `provideRouter(routes)`
* Both `provideRouter` and `withJourniumRouter` must be in the same `bootstrapApplication` call
What's next? [#whats-next]
Learn how to send your own custom events to track user behavior.
Create custom analytics and understand how insights are generated.
# What is Journium (/docs/angular/what-is-journium)
import { RocketIcon } from 'lucide-react';
**Journium** turns raw telemetry into proactive, narrative insights — without charts, queries, or BI. Instead of asking humans to hunt through dashboards, Journium sits on top of your application's data and automatically detects meaningful behavioral changes, explains what happened, and surfaces insights in plain language.
**Data exists. Awareness doesn't.** Journium flips that model.
The Problem We're Solving [#the-problem-were-solving]
Modern applications generate mountains of event data — every click, page view, transaction, and user interaction creates a data point. Yet despite this abundance of information, organizations struggle to extract clear, actionable insights in a timely manner.
The Traditional Analytics Trap [#the-traditional-analytics-trap]
The conventional approach to analytics follows a broken pattern:
**Telemetry → Storage → Queries → Dashboards → Hope**
Teams collect data, store it, build dashboards, and then... hope someone notices something important. This process demands:
* **Manual exploration** — analysts must preprocess data, run queries, and interpret results
* **Domain expertise** — understanding what to look for requires deep knowledge
* **Significant time** — valuable knowledge often remains buried because generating insights traditionally requires significant manual effort
* **Reactive discovery** — by the time an insight is found, it may be too late to act
The result? **We have a data overload, but an insights shortage.** Busy product teams and executives rarely have the luxury to sift through dashboards or craft SQL queries on the fly. Important findings may be discovered too late or not at all.
Why Dashboards Fall Short [#why-dashboards-fall-short]
Static dashboards can show you *what* happened, but they rarely explain *why*. Even specialized BI tools struggle to surface the root causes behind metric movements. You're left with charts that require interpretation, correlation analysis, and often, a bit of guesswork.
How Journium Flips the Narrative [#how-journium-flips-the-narrative]
Journium reimagines analytics from the ground up. Instead of passive reporting tools, we've built an active system that acts like a data analyst working 24/7.
The New Model: Telemetry → Meaning → Action [#the-new-model-telemetry--meaning--action]
Journium follows a simple, powerful principle:
**Telemetry → Meaning → Action**
Not: Telemetry → Storage → Queries → Dashboards → Hope
Your application doesn't need more dashboards. It needs a way to **speak up** when something meaningful changes.
From Passive to Proactive [#from-passive-to-proactive]
Traditional analytics asks: *"What do you want to know?"*\
Journium asks: *"What should you know?"*
Instead of waiting for someone to query the data, Journium continuously monitors your application's behavior, detects significant changes, performs root-cause analysis, and delivers concise insights directly to you — in Slack, email, or wherever you need them.
Think of it this way: Who has the time or interest to dig through charts if an AI can directly tell you *"users from segment X are churning due to feature Y issues, impacting conversion by Z%"* — with the data to back it up?
Insights as Code: The Foundation [#insights-as-code-the-foundation]
Journium introduces **"Insights as Code"** — a novel approach where insights are treated as a first-class, codified product, and an AI-driven engine transforms raw event data into human-ready insights.
What This Means [#what-this-means]
Just as Infrastructure as Code revolutionized how servers and networks are configured, Insights as Code brings software engineering rigor to analytics:
* **Declarative specifications** — Define what you care about in code or configuration, not spreadsheets or Wiki pages
* **Version-controlled** — Track changes, review insights, and maintain consistency across your team
* **Automated generation** — Let AI do the heavy lifting of data crunching, pattern finding, and explanation generation
* **Verifiable and transparent** — Every insight is backed by code and data, making it transparent and trustworthy
The Power of AI-Driven Analysis [#the-power-of-ai-driven-analysis]
Journium leverages Generative AI and large language models to automate insight generation. But this isn't about dumping data into an LLM and hoping for the best. Instead, we use a sophisticated, multi-step approach:
1. **Continuous monitoring** — Track behavioral patterns and detect significant changes
2. **Intelligent analysis** — Use AI agents to pose analytical questions, break them into sub-questions, query data, and synthesize findings
3. **Validation and guardrails** — Ensure insights are both interesting and trustworthy, with automatic validation of claims
4. **Concise delivery** — Generate short, factual takeaways (not long-winded reports) that get straight to the point
This approach ensures insights are **concise, factual takeaways** rather than shallow observations or obvious outliers.
The Vision: An Always-On System [#the-vision-an-always-on-system]
Journium transforms analytics from a reactive process into an **always-on system** that actively drives growth. The vision is simple:
1. **Instrument once** — Integrate Journium's SDK into your application
2. **Define what matters** — Specify your goals and questions in configuration
3. **Receive insights automatically** — Get proactive, narrative insights delivered continuously
The outcome? An analytics experience that feels almost magical: you integrate an SDK, define high-level goals in a config, and the system speaks to you with facts and explanations continuously — almost like a data-savvy colleague working around the clock.
Yet under the hood, every insight is backed by code and data — transparent and verifiable.
Why This Matters [#why-this-matters]
In a world inundated with data, those who can harness AI to tell the story of the data will leap ahead. Journium eliminates the traditional divide between "data collection" and "insight generation," drastically reducing the time from question to answer and empowering teams to be truly data-driven without slogging through dashboards.
The barrier to trying a new analysis becomes so low — just write a new tracker and let the AI do the rest. This unlocks creative uses of analytics that were previously too time-consuming or resource-intensive to pursue.
**Stop looking for insights. Let your application tell you.**
} href="/docs/angular" horizontal="true">
Get Journium integrated into your Angular app in under 5 minutes
# API Methods (/docs/js/api-methods)
API Reference [#api-reference]
Complete reference for all Journium JavaScript SDK methods and functions.
Initialization [#initialization]
init(config) [#initconfig]
Initializes and returns a new JourniumAnalytics instance.
**Parameters:**
| Parameter | Type | Required | Description |
| ----------------------- | ---------------------- | -------- | -------------------------------------------------------------- |
| `config` | `JourniumConfig` | Yes | Configuration object |
| `config.publishableKey` | `string` | Yes | Your Journium publishable key |
| `config.apiHost` | `string` | No | Custom API endpoint (default: `'https://events.journium.app'`) |
| `config.options` | `JourniumLocalOptions` | No | Local configuration options |
**Returns:** `JourniumAnalytics` - Analytics instance for tracking events
**Example:**
```typescript
import { init } from '@journium/js';
const journium = init({
publishableKey: 'pk_your_key_here',
apiHost: 'https://events.journium.app',
options: {
debug: true,
flushAt: 10,
flushInterval: 5000
}
});
```
Event Tracking [#event-tracking]
track(event, properties?) [#trackevent-properties]
Tracks custom events with optional properties.
**Parameters:**
| Parameter | Type | Required | Description |
| ------------ | ------------------------- | -------- | ---------------------------------- |
| `event` | `string` | Yes | Event name to track |
| `properties` | `Record` | No | Event properties (key-value pairs) |
**Returns:** `void`
**Examples:**
**Basic event:**
```typescript
journium.track('button_clicked');
```
**Event with properties:**
```typescript
journium.track('product_viewed', {
product_id: 'prod_123',
product_name: 'Running Shoes',
price: 89.99,
currency: 'USD',
category: 'Footwear'
});
```
**E-commerce purchase:**
```typescript
journium.track('purchase_completed', {
order_id: 'order_789',
revenue: 299.97,
tax: 24.00,
shipping: 10.00,
items: [
{ id: 'prod_123', name: 'Running Shoes', price: 89.99, quantity: 1 },
{ id: 'prod_456', name: 'Sports Watch', price: 209.98, quantity: 1 }
]
});
```
**User action:**
```typescript
journium.track('form_submitted', {
form_name: 'contact_us',
form_location: 'footer',
fields_completed: 4,
newsletter_signup: true
});
```
capturePageview(properties?) [#capturepageviewproperties]
Manually captures pageview events.
**Parameters:**
| Parameter | Type | Required | Description |
| ------------ | ------------------------- | -------- | ------------------- |
| `properties` | `Record` | No | Pageview properties |
**Returns:** `void`
**Examples:**
**Basic pageview:**
```typescript
journium.capturePageview();
```
**Pageview with custom properties:**
```typescript
journium.capturePageview({
page_type: 'product',
category: 'electronics',
product_id: 'prod_123'
});
```
**SPA route change:**
```typescript
router.on('routeChange', (route) => {
journium.capturePageview({
route: route.path,
previous_route: route.from,
page_title: document.title
});
});
```
User Identity [#user-identity]
identify(distinctId, attributes?) [#identifydistinctid-attributes]
Identifies a user and associates future events with their identity.
**Parameters:**
| Parameter | Type | Required | Description |
| ------------ | ------------------------- | -------- | --------------------------------------------- |
| `distinctId` | `string` | Yes | Unique user identifier (email, user ID, etc.) |
| `attributes` | `Record` | No | User attributes (name, email, plan, etc.) |
**Returns:** `void`
**Examples:**
**Basic identification:**
```typescript
journium.identify('user_12345');
```
**With user attributes:**
```typescript
journium.identify('user_12345', {
email: 'john@example.com',
name: 'John Doe',
plan: 'premium',
signup_date: '2024-01-15',
total_purchases: 5,
lifetime_value: 499.95
});
```
**After login:**
```typescript
function handleLogin(user) {
journium.identify(user.id, {
email: user.email,
first_name: user.firstName,
last_name: user.lastName,
role: user.role,
company: user.company
});
}
```
**Update user attributes:**
```typescript
// Identify again to update attributes
journium.identify('user_12345', {
plan: 'enterprise', // Updated plan
last_login: new Date().toISOString()
});
```
reset() [#reset]
Resets user identity, typically called on logout. Clears the current user ID and starts a new session.
**Parameters:** None
**Returns:** `void`
**Example:**
```typescript
function handleLogout() {
// Track logout event
journium.track('user_logged_out');
// Reset identity
journium.reset();
// Redirect to login
window.location.href = '/login';
}
```
```typescript
// In a logout button handler
document.getElementById('logout-btn').addEventListener('click', () => {
journium.reset();
// Perform logout logic
});
```
Autocapture Control [#autocapture-control]
startAutocapture() [#startautocapture]
Starts automatic event capture for clicks, form interactions, and pageviews.
**Parameters:** None
**Returns:** `void`
**Note:** Autocapture behavior is configured during initialization via the `autocapture` option.
**Example:**
```typescript
const journium = init({
publishableKey: 'pk_...',
options: {
autocapture: {
captureClicks: true,
captureFormSubmits: true
}
}
});
// Start capturing after user consent
if (userHasConsented) {
journium.startAutocapture();
}
```
stopAutocapture() [#stopautocapture]
Stops automatic event capture.
**Parameters:** None
**Returns:** `void`
**Example:**
```typescript
// Stop capture when user opts out
function handleOptOut() {
journium.stopAutocapture();
journium.reset();
}
```
```typescript
// Temporarily disable during sensitive operations
journium.stopAutocapture();
// Perform sensitive operation
performPaymentProcessing();
journium.startAutocapture();
```
Event Management [#event-management]
flush() [#flush]
Manually sends all queued events to the server immediately.
**Parameters:** None
**Returns:** `Promise` - Promise that resolves when events are sent
**Examples:**
**Basic flush:**
```typescript
await journium.flush();
```
**Before page unload:**
```typescript
window.addEventListener('beforeunload', async (e) => {
await journium.flush();
});
```
**After critical action:**
```typescript
async function handlePurchase(orderId) {
journium.track('purchase_completed', { order_id: orderId });
// Ensure event is sent before redirect
await journium.flush();
window.location.href = `/order-confirmation/${orderId}`;
}
```
**With error handling:**
```typescript
try {
await journium.flush();
console.log('Events sent successfully');
} catch (error) {
console.error('Failed to send events:', error);
}
```
destroy() [#destroy]
Cleans up the SDK, stops all tracking, flushes remaining events, and removes event listeners.
**Parameters:** None
**Returns:** `void`
**Examples:**
**On app unmount:**
```typescript
// React
useEffect(() => {
return () => {
journium.destroy();
};
}, []);
```
**Manual cleanup:**
```typescript
function cleanupAnalytics() {
journium.destroy();
console.log('Analytics cleaned up');
}
```
Configuration Management [#configuration-management]
getEffectiveOptions() [#geteffectiveoptions]
Returns the current effective configuration options (merged local and remote options).
**Parameters:** None
**Returns:** `JourniumLocalOptions` - Current effective configuration
**Example:**
```typescript
const options = journium.getEffectiveOptions();
console.log('Current configuration:', options);
if (options.debug) {
console.log('Debug mode is enabled');
}
console.log(`Flush after ${options.flushAt} events`);
console.log(`Flush every ${options.flushInterval}ms`);
```
onOptionsChange(callback) [#onoptionschangecallback]
Register a callback to be notified when effective options change (e.g., when remote options are fetched).
**Parameters:**
| Parameter | Type | Required | Description |
| ---------- | ----------------------------------------- | -------- | ------------------------------------ |
| `callback` | `(options: JourniumLocalOptions) => void` | Yes | Function to call when options change |
**Returns:** `() => void` - Unsubscribe function to stop listening to changes
**Examples:**
**Basic usage:**
```typescript
const unsubscribe = journium.onOptionsChange((options) => {
console.log('Options updated:', options);
});
// Later, stop listening
unsubscribe();
```
**React with state:**
```typescript
const [config, setConfig] = useState(null);
useEffect(() => {
const unsubscribe = journium.onOptionsChange((options) => {
setConfig(options);
console.log('Configuration loaded:', options);
});
return () => unsubscribe();
}, []);
```
**Enable features based on remote config:**
```typescript
journium.onOptionsChange((options) => {
if (options.autocapture) {
enableAutocaptureUI();
}
if (options.debug) {
showDebugPanel();
}
});
```
Complete Usage Example [#complete-usage-example]
```typescript
import { init } from '@journium/js';
// 1. Initialize
const journium = init({
publishableKey: 'pk_your_key',
options: {
debug: true,
autocapture: {
captureClicks: true,
captureFormSubmits: true
}
}
});
// 2. Start autocapture
journium.startAutocapture();
// 3. Track custom events
journium.track('app_loaded', {
version: '1.0.0',
platform: 'web'
});
// 4. Identify user after login
function onLogin(user) {
journium.identify(user.id, {
email: user.email,
name: user.name,
plan: user.plan
});
journium.track('user_logged_in', {
login_method: 'email'
});
}
// 5. Track user actions
document.getElementById('buy-button').addEventListener('click', () => {
journium.track('buy_button_clicked', {
product_id: 'prod_123',
location: 'homepage'
});
});
// 6. Reset on logout
function onLogout() {
journium.track('user_logged_out');
journium.reset();
}
// 7. Cleanup on page unload
window.addEventListener('beforeunload', async () => {
await journium.flush();
journium.destroy();
});
```
Browser Console Methods [#browser-console-methods]
For debugging in browser console:
```javascript
// Check if SDK is loaded
console.log(window.journium);
// Get current configuration
console.log(journium.getEffectiveOptions());
// Test tracking
journium.track('console_test_event', { test: true });
// Force send events
await journium.flush();
// View all methods
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(journium)));
```
Error Handling [#error-handling]
The SDK handles errors gracefully, but you can add your own error handling:
```typescript
// Track method calls are fire-and-forget (don't throw)
journium.track('custom_event', { data: 'value' });
// Flush returns a promise you can catch
journium.flush().catch(error => {
console.error('Failed to flush events:', error);
// Maybe retry or log to your error service
});
// Listen for initialization failures
journium.onOptionsChange((options) => {
if (!options || Object.keys(options).length === 0) {
console.warn('Failed to load remote configuration');
}
});
```
TypeScript Support [#typescript-support]
All methods are fully typed. Import types for better IDE support:
```typescript
import {
init,
type JourniumAnalytics,
type JourniumConfig,
type JourniumLocalOptions
} from '@journium/js';
const config: JourniumConfig = {
publishableKey: 'pk_...',
options: {
debug: true
}
};
const analytics: JourniumAnalytics = init(config);
```
Next Steps [#next-steps]
Learn about all configuration options
View complete type definitions
See real-world implementation examples
# CDN / Script Tag Usage (/docs/js/cdn-usage)
import { ShopifyIcon } from '@/components/icons/shopify';
import { WordPressIcon } from '@/components/icons/wordpress';
Overview [#overview]
Add Journium analytics to any website using a simple `
```
Step 2: Track Events [#step-2-track-events]
Once initialized, use the global `journium` object to track events:
```html
```
Static HTML Example [#static-html-example]
```html
My Website
```
Next Steps [#next-steps]
Explore all configuration options and settings
Complete API method documentation
Detailed Shopify store integration guide
Complete WordPress site integration guide
# Configuration Options (/docs/js/configuration)
Configuration Options [#configuration-options]
Configure every aspect of Journium to match your needs. Settings provided in the SDK take precedence over dashboard settings.
Basic Configuration [#basic-configuration]
Initialize Journium with your publishable key and optional configuration:
```ts title="index.ts"
import { init } from '@journium/js';
const journium = init({
publishableKey: 'your-journium-publishable-key',
apiHost: 'https://events.journium.app', // Optional: custom API endpoint
options: {
// Configuration options here
}
});
```
Configuration Options Reference [#configuration-options-reference]
Debug Mode [#debug-mode]
Enable detailed logging for development and troubleshooting.
```typescript
{
debug: true // Default: false
}
```
**When to use:**
* ✅ Development environment
* ✅ Debugging integration issues
* ✅ Verifying events are tracked
* ❌ Production (increases console output)
**Example:**
```typescript
const journium = init({
publishableKey: 'pk_test_...',
options: {
debug: process.env.NODE_ENV === 'development'
}
});
```
Event Batching [#event-batching]
Control how frequently events are sent to the server.
Flush At [#flush-at]
Number of events to accumulate before automatically sending to server.
```typescript
{
flushAt: 20 // Default: 20
}
```
**Recommendations:**
* **High-traffic sites:** 50-100 (reduce server requests)
* **Low-traffic sites:** 10-20 (faster event delivery)
* **Real-time needs:** 1-5 (immediate sending)
Flush Interval [#flush-interval]
Time interval (milliseconds) between automatic flushes.
```typescript
{
flushInterval: 10000 // Default: 10000 (10 seconds)
}
```
**Recommendations:**
* **Standard sites:** 10000-30000ms
* **Real-time dashboards:** 5000-10000ms
* **Low-priority tracking:** 30000-60000ms
**Example - Balanced Configuration:**
```typescript
const journium = init({
publishableKey: 'pk_...',
options: {
flushAt: 20, // Send after 20 events
flushInterval: 10000 // Or every 10 seconds
}
});
```
Session Management [#session-management]
Configure user session behavior and timeout.
```typescript
{
sessionTimeout: 1800000 // Default: 1800000 (30 minutes)
}
```
**Common Values:**
* **30 minutes:** `1800000` (standard)
* **15 minutes:** `900000` (shorter sessions)
* **1 hour:** `3600000` (longer sessions)
* **24 hours:** `86400000` (persistent)
**Use Cases:**
* **E-commerce:** 30-60 minutes (shopping sessions)
* **Content sites:** 30 minutes (reading sessions)
* **SaaS apps:** 2-4 hours (work sessions)
Automatic Pageview Tracking [#automatic-pageview-tracking]
Automatically track pageview events on navigation.
```typescript
{
autoTrackPageviews: true // Default: true
}
```
**When to disable:**
* ❌ Single Page Applications with custom routing
* ❌ When you want full control over pageview tracking
* ✅ Keep enabled for standard websites
**Example - Disable for SPA:**
```typescript
const journium = init({
publishableKey: 'pk_...',
options: {
autoTrackPageviews: false // Manual tracking in SPA
}
});
// Then manually track pageviews
router.on('routeChange', (route) => {
journium.capturePageview({ route });
});
```
Autocapture Configuration [#autocapture-configuration]
Configure automatic capture of user interactions.
Simple Enable/Disable [#simple-enabledisable]
```typescript
{
autocapture: true // or false
}
```
Detailed Configuration [#detailed-configuration]
```typescript
{
autocapture: {
captureClicks: true, // Track click events
captureFormSubmits: true, // Track form submissions
captureFormChanges: false, // Track form field changes
captureTextSelection: false, // Track text selection
ignoreClasses: ['no-track'], // CSS classes to ignore
ignoreElements: ['script', 'style'], // HTML elements to ignore
captureContentText: true // Capture element text content
}
}
```
**Configuration Examples:**
**E-commerce Site:**
```typescript
{
autocapture: {
captureClicks: true,
captureFormSubmits: true,
captureFormChanges: false,
ignoreClasses: ['analytics-ignore', 'no-track'],
ignoreElements: ['input[type="password"]', 'input[type="credit-card"]']
}
}
```
**Blog/Content Site:**
```typescript
{
autocapture: {
captureClicks: true,
captureFormSubmits: true,
captureTextSelection: true, // Track what users highlight
ignoreClasses: ['ad', 'sponsored']
}
}
```
**Privacy-Focused:**
```typescript
{
autocapture: {
captureClicks: true,
captureFormSubmits: false, // No form tracking
captureFormChanges: false,
captureContentText: false, // Don't capture text content
ignoreElements: ['input', 'textarea'] // Ignore all inputs
}
}
```
API Host [#api-host]
Custom API endpoint for self-hosted or regional deployments.
```typescript
{
apiHost: 'https://events.journium.app' // Default
}
```
**Use Cases:**
* **Self-hosted:** `https://analytics.yourcompany.com`
* **Regional compliance:** `https://eu.journium.app`
* **Development:** `http://localhost:3006`
Complete Configuration Example [#complete-configuration-example]
```typescript
import { init } from '@journium/js';
const journium = init({
publishableKey: process.env.JOURNIUM_KEY!,
apiHost: 'https://events.journium.app',
options: {
// Development & Debugging
debug: process.env.NODE_ENV === 'development',
// Performance & Batching
flushAt: 20,
flushInterval: 10000,
// Session Management
sessionTimeout: 1800000, // 30 minutes
// Automatic Tracking
autoTrackPageviews: true,
// Autocapture Configuration
autocapture: {
captureClicks: true,
captureFormSubmits: true,
captureFormChanges: false,
captureTextSelection: false,
ignoreClasses: ['no-track', 'analytics-ignore'],
ignoreElements: [
'input[type="password"]',
'input[type="credit-card"]',
'script',
'style'
],
captureContentText: true
}
}
});
// Start automatic capture
journium.startAutocapture();
```
Next Steps [#next-steps]
Explore all available methods and functions
View complete type definitions and interfaces
Platform-specific configuration examples
# How Journium Works (/docs/js/how-journium-works)
Journium works by collecting [Events](/docs/react/concepts/events) from your application and then using AI to generate insights
from those events. Users integrate the Journium SDK into their applications, which sends events
to Journium's API where they are ingested and processed. Users then create [Insight Trackers](/docs/react/concepts/insight-trackers) that define
the mechanics around how [Insights](/docs/react/concepts/insights) should be generated, and [Jobs](/docs/react/concepts/jobs)
execute those trackers to produce insights. These insights are then available on the Journium dashboard for users to view and analyze.
Journium Workflow [#journium-workflow]
Event Collection [#event-collection]
Event collection is the foundation of Journium's analytics pipeline. Users integrate
the Journium SDK into their applications, which acts as a lightweight client library
that captures user interactions and application events. When events occur in your
application—such as user signups, purchases, feature usage, or errors—the SDK automatically
sends these events to Journium's API endpoint. The API receives and ingests these events,
storing them in a time-series database optimized for analytics queries. This continuous
stream of event data provides the raw material that powers all subsequent analysis
and insight generation.
Tracker Definition [#tracker-definition]
Trackers are declarative configurations that define what should be analyzed and how insights
should be generated. Users create trackers through the Journium dashboard, specifying
which events to monitor (or analyzing all events), setting custom instructions for
the AI analysis, and configuring execution schedules. Each tracker acts like a continuous
data analyst that monitors specific patterns in your event data. Trackers can be set to
run automatically on a schedule (e.g., hourly, daily, weekly) or triggered manually
for ad-hoc analysis. The tracker configuration includes parameters such as the maximum number
of events to analyze, custom AI instructions that guide the analysis focus, and the
specific event types to consider. This "Insights as Code" approach allows users to define
what they want to know about their application without writing SQL queries or building dashboards.
Job Execution [#job-execution]
Job execution is the automated process that runs trackers and generates insights. When a tracker
is scheduled to run or manually triggered, Journium creates a job that executes the tracker's
analysis workflow. The job execution follows a multi-step pipeline: it first validates the
tracker configuration and checks data availability, then queries the event database to
retrieve the relevant events based on the tracker's configuration. The job then uses AI
to analyze the event data, looking for patterns, trends, anomalies, and correlations. The
AI engine processes the data according to the tracker's instructions, synthesizing findings
into concise, natural language insights that are typically 1-3 sentences long and backed
by verifiable data. Finally, the job stores the generated insights and updates the execution
history, making them ready for display in the dashboard.
Insights Display [#insights-display]
Once insights are generated by job execution, they become available in the Journium dashboard
for users to view and analyze. Insights are displayed in a feed format on the application instance's
insights page, similar to a social media feed, where each insight appears as a card showing the
analysis results, timestamp, and metadata. Users can interact with insights by liking them, adding
comments for team collaboration, saving them for later reference, or sharing them with team members.
The dashboard also provides features like pagination to browse through historical insights,
filtering options, and the ability to see insight trends over time. This presentation format makes
insights easily scannable and actionable, transforming raw event data into understandable narratives
that help teams make data-driven decisions about their application.
# JavaScript Quick Start (/docs/js)
import { ShopifyIcon } from '@/components/icons/shopify';
import { WordPressIcon } from '@/components/icons/wordpress';
import { Settings, Code, FileCode } from 'lucide-react'
Installation [#installation]
We recommend one of the framework specific integrations for the best experience.
Choose the installation method that best fits your project:
**Ideal for websites without build tools.**
```html title="index.html"
```
Perfect for:
* Static HTML websites
* Shopify stores
* WordPress sites
* No-code platforms
For detailed CDN usage including e-commerce tracking examples and advanced configurations, see the [CDN Usage Guide](/docs/js/cdn-usage).
**Recommended for modern web applications with build tools.**
```bash title="Terminal"
npm install @journium/js
```
Perfect for applications using:
* Webpack, Vite, or other bundlers
* TypeScript projects
* Modern JavaScript frameworks
Set your Journium Publishable Key [#set-your-journium-publishable-key]
1. **Sign up for a Journium account** for free at [journium.app/signup](https://journium.app/signup)
2. **[Create an application](https://dashboard.journium.app/apps/new)** in your Journium dashboard
3. **Copy your Publishable Key** from the [Developers | API Keys](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/api-keys) section
Dashboard URLs automatically navigate to your app - just click!
Initialize Journium [#initialize-journium]
Initialize the Journium SDK with your publishable key to start tracking events.
```html title="index.html"
```
```ts title="index.ts"
import { init } from '@journium/js';
const journium = init({
publishableKey: 'your-journium-publishable-key'
});
```
Track a Custom Event [#track-a-custom-event]
Track user actions and business events with custom properties.
```html title="index.html"
```
```ts title="index.ts"
journium.track('button_clicked', {
button_name: 'signup',
page: 'homepage',
user_type: 'visitor'
});
```
Identify a User [#identify-a-user]
Identify users when they log in or sign up to connect their actions across sessions.
```html title="index.html"
```
```ts title="index.ts"
journium.identify('user_12345', {
name: 'John Doe',
email: 'john@example.com',
plan: 'premium'
});
```
Reset User Identity [#reset-user-identity]
Reset user identity when they log out to ensure privacy and accurate tracking.
```html title="index.html"
```
```ts title="index.ts"
journium.reset();
```
Send Events to Journium [#send-events-to-journium]
Navigate around your app to automatically send events to Journium.
Then view your collected events at [Developers | Events](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/events).
**Success indicator:** You should see events appearing in your dashboard within a few seconds.
Generate Your First Insight [#generate-your-first-insight]
When you create an app in Journium, a default [Insight Tracker](/docs/react/concepts/insight_trackers) is automatically created.
This tracker helps you test data ingestion and insight generation.
1. Go to your [Developers | Insight Trackers](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/insight-trackers) page
2. Click the **`Analyze now`** button for the tracker titled **"User Engagement"**
3. Monitor the job status in [Developers | Jobs](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/developers/jobs)
4. Wait for the job to complete (usually takes 1-2 minutes)
5. View your generated insights at [Dashboard | Insights](https://dashboard.journium.app/apps/j_app~/instances/j_app_inst~/insights)
Done [#done]
**Congratulations!** You've successfully created your first insight with Journium!
Troubleshooting [#troubleshooting]
* Verify your API key starts with `pk_` and is correctly set in your code
* Check browser console for errors (F12 → Console)
* Ensure you're interacting with your **local app** (not the dashboard)
* Delete `node_modules` and reinstall dependencies:
```bash
rm -rf node_modules && npm install
```
* Ensure Node.js version is 18+:
```bash
node --version
```
Platform-Specific Guides [#platform-specific-guides]
} href="/docs/js/shopify-integration">
Track product views, cart events, and purchases on your Shopify store
} href="/docs/js/wordpress-integration">
Add analytics to your WordPress site and track blog engagement
API Documentation [#api-documentation]
}>
Complete guide to all configuration options and settings
}>
>
All methods, parameters, and usage examples
}>
>
Complete type definitions for TypeScript projects
What's next? [#whats-next]
Learn how to send your own custom events to track user behavior.
Create custom analytics and understand how insights are generated.
# Shopify Integration (/docs/js/shopify-integration)
Shopify Analytics Integration [#shopify-analytics-integration]
Integrate Journium analytics with your Shopify store to track product views, cart events, purchases, and customer behavior.
Installation [#installation]
Step 1: Get Your Journium Publishable Key [#step-1-get-your-journium-publishable-key]
1. Create a Shopify application in your Journium Dashboard
2. Copy your Publishable Key from the API Keys section
Step 2: Add Journium to Your Shopify Theme [#step-2-add-journium-to-your-shopify-theme]
1. **Log in to your Shopify Admin**
2. Go to **Online Store → Themes**
3. Click **Actions → Edit code** on your active theme
4. Open **Layout → theme.liquid**
5. **Add this code before ``**:
```html
```
6. **Click Save**
Step 3: Track E-commerce Events [#step-3-track-e-commerce-events]
Add tracking for key shopping events by adding code to specific template files.
Product View Tracking [#product-view-tracking]
Track when customers view products to understand which products generate interest.
**File:** `Templates → product.liquid` (or in your product template section)
```html
```
Collection View Tracking [#collection-view-tracking]
Track collection page views to see which categories interest customers.
**File:** `Templates → collection.liquid`
```html
```
Add to Cart Tracking [#add-to-cart-tracking]
Track when products are added to cart - critical for conversion analysis.
**Option 1: Using Theme Customization (Recommended)**
1. Go to **Online Store → Themes → Customize**
2. Open **Theme settings → Custom CSS** (or equivalent)
3. Use browser console to find your add-to-cart button selector
4. Add this to **Layout → theme.liquid** before `