Skip to main content

Overview

The User Context API allows you to send contextual information to the assistant from anywhere in your application. This works across all frameworks and provides real-time context to both voice and chat interactions.

Basic Usage

import { sendUserContext } from "navi-web";

// Silent contextual message (default) - provides background context to AI
sendUserContext("User viewing order #12345, status: pending, total: $299.99");

// User message - appears as an actual message in the chat conversation
sendUserContext("I need help with this order", { silent: false });

Context Types

Silent Messages (Default)

Silent messages provide background context to the AI without appearing in the chat interface:
// These won't show up in the chat UI but inform the AI about user state
sendUserContext("User on pricing page, viewing premium plan");
sendUserContext("Form validation failed: email field empty");
sendUserContext("User scrolled to testimonials section");

User Messages

User messages appear as actual messages in the chat conversation:
// These will appear as user messages in the chat
sendUserContext("I'm having trouble with checkout", { silent: false });
sendUserContext("Can you help me find the refund policy?", { silent: false });

Framework Examples

React Examples

E-commerce Product Page

import React, { useEffect } from "react";
import { sendUserContext } from "navi-web";

const ProductPage = ({ product }) => {
  // Send context when user views a product
  useEffect(() => {
    if (product) {
      sendUserContext(
        `User viewing product: ${product.name}, price: $${product.price}, category: ${product.category}`
      );
    }
  }, [product]);

  // Send context based on user actions
  const handleAddToCart = () => {
    sendUserContext(`User added ${product.name} to cart`);
    // ... your add to cart logic
  };

  const handleGetHelp = () => {
    sendUserContext("I need help with this product", { silent: false });
  };

  return (
    <div>
      <h1>{product.name}</h1>
      <button onClick={handleAddToCart}>Add to Cart</button>
      <button onClick={handleGetHelp}>Get Help</button>
    </div>
  );
};

User Dashboard

import React from "react";
import { sendUserContext } from "navi-web";

const Dashboard = ({ user, orders, notifications }) => {
  // Send user state context when dashboard loads
  React.useEffect(() => {
    sendUserContext(
      `User dashboard loaded: ${orders.length} orders, ${notifications.length} unread notifications`
    );
  }, [orders.length, notifications.length]);

  const handleOrderClick = (order) => {
    sendUserContext(
      `User clicked on order ${order.id}, status: ${order.status}`
    );
  };

  return (
    <div>
      {orders.map((order) => (
        <div key={order.id} onClick={() => handleOrderClick(order)}>
          Order #{order.id}
        </div>
      ))}
    </div>
  );
};

Vue.js Examples

Shopping Cart Component

<template>
  <div>
    <h2>Shopping Cart ({{ items.length }} items)</h2>
    <div v-for="item in items" :key="item.id" @click="viewItem(item)">
      {{ item.name }} - ${{ item.price }}
    </div>
    <button @click="checkout" v-if="items.length > 0">
      Checkout (${{ totalPrice }})
    </button>
  </div>
</template>

<script>
import { sendUserContext } from 'navi-web';

export default {
  props: ['items'],
  computed: {
    totalPrice() {
      return this.items.reduce((sum, item) => sum + item.price, 0);
    }
  },
  watch: {
    items: {
      handler(newItems) {
        if (newItems.length > 0) {
          sendUserContext(`Cart updated: ${newItems.length} items, total: $${this.totalPrice}`);
        }
      },
      deep: true
    }
  },
  methods: {
    viewItem(item) {
      sendUserContext(`User viewing cart item: ${item.name}`);
    },
    checkout() {
      sendUserContext("User starting checkout process");
      // ... checkout logic
    }
  }
};
</script>

Advanced Usage Patterns

Error Context

try {
  await submitForm(data);
  sendUserContext("Form submitted successfully");
} catch (error) {
  sendUserContext(`Form submission failed: ${error.message}`);
}
// React Router
const router = useRouter();
useEffect(() => {
  sendUserContext(`User navigated to ${router.pathname}`);
}, [router.pathname]);

// Vue Router
watch(
  () => route.path,
  (newPath) => {
    sendUserContext(`User navigated to ${newPath}`);
  }
);

Feature Usage Context

const handleFeatureUsage = (featureName) => {
  sendUserContext(`User used feature: ${featureName}`);
};

// Track specific interactions
sendUserContext("User opened advanced search filters");
sendUserContext("User downloaded report PDF");
sendUserContext("User enabled dark mode");

Search and Filter Context

// Search context
const handleSearch = (query, resultsCount) => {
  sendUserContext(`Search performed: "${query}", ${resultsCount} results found`);
};

// Filter context
const handleFilterChange = (filters) => {
  const activeFilters = Object.entries(filters)
    .filter(([_, value]) => value)
    .map(([key]) => key);
  sendUserContext(`Filters applied: ${activeFilters.join(", ")}`);
};

// Pagination context
const handlePageChange = (page, totalPages) => {
  sendUserContext(`User on page ${page} of ${totalPages}`);
};

Best Practices

Do’s

// Good examples - descriptive and actionable
sendUserContext("User viewing order #12345, status: shipped, tracking: ABC123");
sendUserContext("Search performed: 'wireless headphones', 24 results found");
sendUserContext("User applied discount code 'SAVE20', 20% off applied");
sendUserContext("Shopping cart has 3 items, total: $147.99");

Don’ts

// Avoid over-detailed context
// sendUserContext("Mouse moved to position 150,200"); // Too granular
// sendUserContext("User scrolled 50px"); // Not meaningful
// sendUserContext("Button hover state changed"); // Too frequent

Guidelines

  1. Be Descriptive: Provide meaningful context that helps the AI understand user intent
  2. Include Relevant Data: Send IDs, statuses, amounts, and other relevant information
  3. Use Silent by Default: Most context should be silent unless it’s an actual user request
  4. Don’t Over-Send: Send context for meaningful events, not every mouse movement
  5. Format Consistently: Use consistent formatting for similar types of context

Multi-Page Applications (MPA) Support

In multi-page applications, context is queued and persists across page reloads:
// This works even before the widget is initialized
sendUserContext("User came from Google search for 'product reviews'");

// Context persists for ~5 minutes across page navigation
sendUserContext("User previously viewed 5 products in Electronics category");

CDN Usage

When using the CDN version, the API is available on window.Navi:
// Works anywhere after the CDN script loads
Navi.sendUserContext("User viewing order #123, total: $299");

// User message mode
Navi.sendUserContext("I need help with this order", { silent: false });

Complete Example

Here’s a comprehensive example showing context usage throughout a user journey:
import { sendUserContext } from "navi-web";

// Page load context
useEffect(() => {
  sendUserContext(`User on ${window.location.pathname}, referrer: ${document.referrer}`);
}, []);

// User authentication context
useEffect(() => {
  if (user) {
    sendUserContext(`User logged in: ${user.email}, account type: ${user.type}`);
  }
}, [user]);

// Product interaction context
const handleProductView = (product) => {
  sendUserContext(`Viewing ${product.name}, price: $${product.price}, in stock: ${product.stock > 0}`);
};

const handleAddToCart = (product) => {
  sendUserContext(`Added ${product.name} to cart, cart now has ${cartItems.length + 1} items`);
};

// Search context
const handleSearch = (query) => {
  sendUserContext(`Searching for: "${query}"`);
};

// Error context
const handleError = (error, context) => {
  sendUserContext(`Error in ${context}: ${error.message}`);
};

// User help request
const handleHelpRequest = () => {
  sendUserContext("I need help finding the right product for my needs", { silent: false });
};