Examples

Real-world context helper implementations

Practical examples of context helpers for common use cases.

E-commerce Context

const cartHelper = async () => ({
  itemCount: getCartItemCount(),
  totalValue: getCartTotal(),
  items: getCartItems().map((item) => ({
    id: item.id,
    name: item.name,
    price: item.price,
  })),
});

const preferencesHelper = async () => ({
  currency: getUserCurrency(),
  shippingAddress: await getUserShippingAddress(),
  paymentMethods: (await getSavedPaymentMethods()).length,
});

// Register globally with TamboProvider
<TamboProvider
  contextHelpers={{
    cart: cartHelper,
    userPreferences: preferencesHelper,
  }}
/>;

// Or register locally per page/layout with TamboContextHelpersProvider
<TamboContextHelpersProvider
  contextHelpers={{
    cart: cartHelper,
    userPreferences: preferencesHelper,
  }}
/>;

Analytics Context

const analyticsHelper = async () => ({
  sessionDuration: getSessionDuration(),
  pageViews: getPageViewCount(),
  referrer: document.referrer,
  utm_params: getUTMParameters(),
  userSegment: await getUserSegment(),
});

// Local registration example
<TamboContextHelpersProvider
  contextHelpers={{
    analytics: analyticsHelper,
  }}
/>;

Location-Based Context

const locationHelper = async () => {
  try {
    const position: GeolocationPosition = await new Promise(
      (resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
      },
    );

    return {
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      accuracy: position.coords.accuracy,
    };
  } catch {
    return { error: "Location unavailable" };
  }
};

// Register only where geolocation is needed
<TamboContextHelpersProvider
  contextHelpers={{
    location: locationHelper,
  }}
/>;

Authentication Context

const authHelper = async () => {
  const user = await getCurrentUser();
  return {
    isAuthenticated: !!user,
    userId: user?.id,
    role: user?.role,
    permissions: user?.permissions || [],
    organizationId: user?.organizationId,
  };
};

// Either global or page-scoped
<TamboContextHelpersProvider
  contextHelpers={{
    auth: authHelper,
  }}
/>;

Feature Flags Context

const featureHelper = async () => ({
  flags: await getFeatureFlags(),
  experiments: await getActiveExperiments(),
  userCohort: getUserCohort(),
});

<TamboContextHelpersProvider
  contextHelpers={{
    features: featureHelper,
  }}
/>;

Multi-tenant Context

const tenantHelper = async () => {
  const tenant = await getCurrentTenant();
  return {
    tenantId: tenant.id,
    tenantName: tenant.name,
    subscription: tenant.subscriptionTier,
    customizations: tenant.customSettings,
  };
};

<TamboContextHelpersProvider
  contextHelpers={{
    tenant: tenantHelper,
  }}
/>;

Complete Example

import { TamboProvider, TamboContextHelpersProvider } from "@tambo-ai/react";
import {
  currentTimeContextHelper,
  currentPageContextHelper,
} from "@tambo-ai/react";

const sessionHelper = async () => ({
  sessionId: getSessionId(),
  startTime: getSessionStartTime(),
  duration: getSessionDuration(),
});

const userHelper = async () => ({
  id: getUserId(),
  role: getUserRole(),
  preferences: await getUserPreferences(),
});

const appHelper = () => ({
  version: APP_VERSION,
  environment: process.env.NODE_ENV,
  buildTime: BUILD_TIMESTAMP,
});

function App() {
  return (
    <TamboProvider
      apiKey={process.env.NEXT_PUBLIC_TAMBO_API_KEY!}
      contextHelpers={{
        // Prebuilt helpers (global)
        userTime: currentTimeContextHelper,

        // Custom helpers (global)
        session: sessionHelper,
        user: userHelper,
        app: appHelper,
      }}
    >
      {/* Page-level overrides/additions */}
      <TamboContextHelpersProvider
        contextHelpers={{
          // Override or add page-specific helpers
          userPage: currentPageContextHelper,
          // Optionally override an existing key from the root
          // session: async () => ({ ...customSessionForThisPage })
        }}
      >
        <YourApp />
      </TamboContextHelpersProvider>
    </TamboProvider>
  );
}