Skip to content

Install on React with Vite

Add Loomduct to a React app built with Vite.

Add Loomduct to a React app built with Vite. Page views are tracked on load and on every route change, with React Router or any router that uses the History API.

Install with your AI agent

Add Loomduct analytics to this project. Follow the steps in https://loomduct.com/docs/install/ai-agent.md Ask me for the project token. Do not read .env files.

Before you start

  • A Loomduct project and its project token. In the dashboard, open the project menu, select Project settings, then Copy project token.

Steps

Install the package

npm install @loomduct/js

Add the token to your environment

.env.local
VITE_LOOMDUCT_TOKEN=lmt_your_project_token

Create one instance

src/loomduct.ts
import { Loomduct } from '@loomduct/js'
import { webAnalytics } from '@loomduct/js/web-analytics'

export const loomduct = new Loomduct({
  token: import.meta.env.VITE_LOOMDUCT_TOKEN,
  plugins: [webAnalytics()],
})

Call load() in main.tsx

Call load() before you render the app:

src/main.tsx
import { createRoot } from 'react-dom/client'

import { App } from './App'
import { loomduct } from './loomduct'

loomduct.load()

createRoot(document.getElementById('root')!).render(<App />)

Call it at the top level of the file, not in a component or an effect, so it runs once.

Track events from components

src/upgrade-button.tsx
import { loomduct } from './loomduct'

export function UpgradeButton() {
  return (
    <button onClick={() => loomduct.track('upgrade_clicked')}>Upgrade</button>
  )
}

Check that it worked

  1. Deploy the app and open it in a new tab. Loomduct skips localhost; to test with npm run dev, add allowLocalhost: true to the options for a moment.
  2. Open your project in the dashboard. Your visit shows up as online now on the Overview.

If you turn on allowLocalhost, hot reloads can leave two instances running. Stop the old one when the module reloads:

src/loomduct.ts
import.meta.hot?.dispose(() => loomduct.destroy())