React & Next.js Installation

Install Narrowbeam in React and Next.js applications using npm or script tag.

Installation Options

You can install Narrowbeam in two ways:

  • NPM Package (Recommended) - Better for TypeScript support and tree-shaking
  • Script Tag - Simpler setup, works with any framework

Next.js Installation

Option 1: NPM Package (Recommended)

Install the package:

npm install @narrowbeam/browser

For App Router (Next.js 13+), create a client component in components/analytics.tsx:

'use client';

import { narrowbeam } from '@narrowbeam/browser';

narrowbeam.init({
  orgKey: process.env.NEXT_PUBLIC_NARROWBEAM_ORG_KEY || ''
});

export default function Analytics() {
  return null;
}

Then import it in your app/layout.tsx:

import Analytics from '@/components/analytics';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Analytics />
        {children}
      </body>
    </html>
  );
}

Option 2: Script Tag

Add the script to app/layout.tsx using Next.js Script component:

import Script from 'next/script';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        <Script id="narrowbeam">{`
          (function(w,d,e,s,n) {
            w=w[n]=w[n]||{q:[],onReady:function(c){w.q.push(c)}};
            e=d.createElement(e);e.async=1;e.src=s;
            s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(e,s);
          })(window,document,'script','https://unpkg.com/@narrowbeam/browser/dist/narrowbeam.min.js','narrowbeam');

          window.narrowbeam.onReady(function() {
            window.narrowbeam.init({
              orgKey: '${process.env.NEXT_PUBLIC_NARROWBEAM_ORG_KEY}'
            });
          });
        `}</Script>
      </head>
      <body>{children}</body>
    </html>
  );
}

Pages Router (Next.js 12 and earlier)

For Pages Router, use the same NPM approach by creating an analytics component, or use the inline script in pages/_document.tsx:

import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html>
      <Head>
        <script
          dangerouslySetInnerHTML={{
            __html: `
              (function(w,d,e,s,n) {
                w=w[n]=w[n]||{q:[],onReady:function(c){w.q.push(c)}};
                e=d.createElement(e);e.async=1;e.src=s;
                s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(e,s);
              })(window,document,'script','https://unpkg.com/@narrowbeam/browser/dist/narrowbeam.min.js','narrowbeam');
              window.narrowbeam.onReady(function() {
                window.narrowbeam.init({
                  orgKey: '${process.env.NEXT_PUBLIC_NARROWBEAM_ORG_KEY}'
                });
              });
            `,
          }}
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Create React App Installation

Option 1: NPM Package (Recommended)

Install the package:

npm install @narrowbeam/browser

Create src/analytics.ts:

import { narrowbeam } from '@narrowbeam/browser';

narrowbeam.init({
  orgKey: process.env.REACT_APP_NARROWBEAM_ORG_KEY || ''
});

Import it in src/index.tsx:

import './analytics';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);

Option 2: Script Tag

Add the script to public/index.html in the <head> section:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
    <script>
      (function(w,d,e,s,n) {
        w=w[n]=w[n]||{q:[],onReady:function(c){w.q.push(c)}};
        e=d.createElement(e);e.async=1;e.src=s;
        s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(e,s);
      })(window,document,'script','https://unpkg.com/@narrowbeam/browser/dist/narrowbeam.min.js','narrowbeam');
      window.narrowbeam.onReady(function() {
        window.narrowbeam.init({
          orgKey: 'YOUR_ORG_KEY'
        });
      });
    </script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Vite + React Installation

For Vite, the installation is the same as Create React App - use either NPM package or script tag in index.html.

SPA Navigation Tracking

Good news! Narrowbeam automatically tracks Single Page Application (SPA) navigation. When users navigate in your React app using React Router or Next.js routing, page views are automatically captured.

Automatic SPA Tracking

Narrowbeam intercepts history.pushState and history.replaceState to track client-side navigation. No additional configuration needed!

Tracking Custom Events in React

With NPM Package

Import and use the narrowbeam API directly:

import { narrowbeam } from '@narrowbeam/browser';

function SignUpButton() {
  const handleClick = () => {
    narrowbeam.trackAction('signup-clicked');
    // Your sign-up logic here
  };

  return <button onClick={handleClick}>Sign Up</button>;
}

With Script Tag

Use the global API with the onReady callback:

function SignUpButton() {
  const handleClick = () => {
    window.narrowbeam?.trackAction('signup-clicked');
    // Your sign-up logic here
  };

  return <button onClick={handleClick}>Sign Up</button>;
}

Using Data Attributes

For simpler tracking without JavaScript:

function SignUpButton() {
  return (
    <button data-narrowbeam-action-name="signup-clicked">
      Sign Up
    </button>
  )
}

TypeScript Support

The @narrowbeam/browser package includes TypeScript definitions. If using the script tag, add type definitions:

// types/narrowbeam.d.ts
interface Window {
  narrowbeam?: {
    init: (config: { orgKey: string }) => void;
    trackAction: (actionName: string) => void;
    trackPageView: () => void;
    checkPageChange: () => void;
    onReady: (callback: () => void) => void;
  };
}

Environment Variables

Use environment variables for your organization key across different environments:

# .env.local
NEXT_PUBLIC_NARROWBEAM_ORG_KEY=your-org-key-here
REACT_APP_NARROWBEAM_ORG_KEY=your-org-key-here # For CRA

Next Steps