@lognitor/react
The React SDK wraps @lognitor/browser and provides React-specific components: an error boundary, a context provider, and hooks.
Installation
npm install @lognitor/reactQuick Start
import { LognitorProvider, LognitorErrorBoundary } from '@lognitor/react';
import { useLognitor } from '@lognitor/react';
function App() {
return (
<LognitorProvider
apiKey="your-api-key"
service="my-react-app"
environment="production"
>
<LognitorErrorBoundary fallback={<ErrorPage />}>
<MainContent />
</LognitorErrorBoundary>
</LognitorProvider>
);
}
function MainContent() {
const lognitor = useLognitor();
const handleClick = () => {
lognitor.info('Button clicked', { metadata: { button: 'signup' } });
};
return <button onClick={handleClick}>Sign Up</button>;
}Logging Outside Components
The useLognitor() hook only works inside React components. For utility functions, API helpers, stores, or any non-component code, import directly:
// utils/api.js — no React, no hooks needed
import Lognitor from '@lognitor/react';
export async function fetchUsers() {
try {
const res = await fetch('/api/users');
return await res.json();
} catch (err) {
Lognitor.captureException(err, { metadata: { endpoint: '/api/users' } });
throw err;
}
}All import styles share the same singleton initialized by <LognitorProvider>.
LognitorProvider
The provider initializes the SDK and passes the client to all child components via React context.
import { LognitorProvider } from '@lognitor/react';
function App() {
return (
<LognitorProvider
apiKey="your-api-key"
service="my-react-app"
environment="production"
version="2.1.0"
captureConsole={true}
captureErrors={true}
captureFetch={true}
redactPatterns={['email', 'creditCard']}
beforeSend={(log) => {
if (log.message.includes('dev-only')) return null;
return log;
}}
>
{/* your app */}
</LognitorProvider>
);
}All configuration options from the Browser SDK are accepted as props.
Error Boundary
Catches React rendering errors and automatically sends them to Lognitor.
import { LognitorErrorBoundary } from '@lognitor/react';
// Basic usage
<LognitorErrorBoundary fallback={<div>Something went wrong.</div>}>
<MyComponent />
</LognitorErrorBoundary>
// With custom fallback component
<LognitorErrorBoundary
fallback={({ error, resetError }) => (
<div>
<h2>Error: {error.message}</h2>
<button onClick={resetError}>Try Again</button>
</div>
)}
beforeCapture={(error, errorInfo) => {
console.log('Component stack:', errorInfo.componentStack);
}}
onError={(error, errorInfo) => {
analytics.track('react_error', { component: errorInfo.componentStack });
}}
>
<MyComponent />
</LognitorErrorBoundary>Props
| Prop | Type | Description |
|---|---|---|
fallback | ReactNode or Function | UI to render when an error is caught. Function receives error and resetError. |
beforeCapture | (error, errorInfo) => void | Hook to run before error is sent to Lognitor. |
onError | (error, errorInfo) => void | Hook to run after error is captured. |
useLognitor Hook
import { useLognitor } from '@lognitor/react';
function CheckoutPage() {
const lognitor = useLognitor();
useEffect(() => {
lognitor.info('Checkout page viewed', {
metadata: { cartItems: cart.length },
});
}, []);
const handlePayment = async () => {
const timer = lognitor.startTimer();
try {
await processPayment();
timer.end('Payment successful');
} catch (err) {
lognitor.captureException(err, {
metadata: { amount: cart.total },
tags: ['payment', 'critical'],
});
}
};
return <button onClick={handlePayment}>Pay Now</button>;
}Available Methods
The hook returns the full Lognitor client: log, debug, info, warn, error, fatal, captureException, setUser, clearUser, setContext, setTags, setSession, addBreadcrumb, startTimer, heartbeat, registerRelease, submitFeedback, showReportDialog, flush, shutdown, pause, resume, reconfigure, and child.
Setting User on Login
function LoginForm() {
const { setUser } = useLognitor();
const handleLogin = async (credentials) => {
const user = await api.login(credentials);
setUser({ id: user.id, email: user.email, name: user.name });
};
return <form onSubmit={handleLogin}>{/* ... */}</form>;
}Tracking Route Changes (React Router)
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useLognitor } from '@lognitor/react';
function RouteTracker() {
const location = useLocation();
const { setContext, addBreadcrumb } = useLognitor();
useEffect(() => {
setContext({ page: location.pathname });
addBreadcrumb({
type: 'navigation',
category: 'route',
message: `Navigated to ${location.pathname}`,
level: 'info',
});
}, [location.pathname]);
return null;
}
// In your app:
<BrowserRouter>
<RouteTracker />
<Routes>{/* ... */}</Routes>
</BrowserRouter>Error Boundary Per Route
<Routes>
<Route path="/dashboard" element={
<LognitorErrorBoundary fallback={<DashboardError />}>
<Dashboard />
</LognitorErrorBoundary>
} />
<Route path="/settings" element={
<LognitorErrorBoundary fallback={<SettingsError />}>
<Settings />
</LognitorErrorBoundary>
} />
</Routes>With Next.js (App Router)
// app/providers.tsx
'use client';
import { LognitorProvider, LognitorErrorBoundary } from '@lognitor/react';
export function Providers({ children }) {
return (
<LognitorProvider
apiKey="your-api-key"
service="my-nextjs-app"
environment={process.env.NODE_ENV}
>
<LognitorErrorBoundary fallback={<div>Error occurred</div>}>
{children}
</LognitorErrorBoundary>
</LognitorProvider>
);
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({ children }) {
return (
<html>
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}For Next.js server-side API routes, use @lognitor/node with createNextjsWrapper. The React SDK is for client-side only.