Adding User Context
The Context API lets you tell Pillar what the user is doing, enabling smarter, more relevant assistance and action filtering.
Build with AI
# Identify Pillar Context for My App
Analyze my codebase and determine what context to sync to Pillar for smarter AI assistance.
## What Context Does
Context helps Pillar's AI:
- Know what page/feature the user is viewing
- Filter actions based on user role or permissions
- Provide more relevant answers based on user state
- Understand errors the user is experiencing
## Analyze My App For
### 1. Authentication Patterns
- Where is auth state stored? (useAuth hook, context, Redux, etc.)
- What user properties exist? (role, permissions, subscription status)
- How do I detect admin vs regular users?
### 2. Routing Structure
- What router am I using? (Next.js, React Router, etc.)
- How can I get the current pathname?
- Are there meaningful route segments (e.g., /projects/:id)?
### 3. User State
- Subscription/plan information
- Onboarding status
- Feature flags or entitlements
### 4. Error Handling
- How are errors displayed to users?
- Can we capture error context for AI troubleshooting?
## Generate Components
### RouteContextSync
Sync current route on every navigation:
```tsx
export function RouteContextSync() {
const { pillar } = usePillar();
const pathname = usePathname(); // or useLocation()
useEffect(() => {
pillar?.setContext({ currentPage: pathname });
}, [pillar, pathname]);
return null;
}
```
### UserContextSync
Sync user role and state:
```tsx
export function UserContextSync() {
const { pillar } = usePillar();
const { user } = useAuth(); // Use my actual auth hook
useEffect(() => {
if (user && pillar) {
pillar.setContext({
userRole: user.role,
userState: user.subscriptionStatus,
custom: { plan: user.plan },
});
}
}, [pillar, user]);
return null;
}
```
### Error Context Integration
Hook into my error boundaries or toast system to pass errors to Pillar.
## Start Here
1. Find my auth hook/context
2. Find my routing setup
3. Look for user role/permission patterns
4. Generate the sync components using my actual code patterns
Basic Usage
React
import { usePillar } from '@pillar-ai/react';function SettingsPage() {const { pillar } = usePillar();useEffect(() => {pillar?.setContext({currentPage: '/settings',currentFeature: 'Account Settings',userRole: 'admin',});}, [pillar]);return <Settings />;}
Vanilla JavaScript
Important:
setContextis an instance method, not a static method. UsePillar.getInstance()to get the SDK instance after initialization.
// Get the SDK instance (after Pillar.init() has completed)const pillar = Pillar.getInstance();// Set context when the page loads or changespillar?.setContext({currentPage: window.location.pathname,currentFeature: 'Account Settings',userRole: 'admin',});// Update context on navigation (for SPAs)window.addEventListener('popstate', () => {pillar?.setContext({ currentPage: window.location.pathname });});
Context Properties
| Property | Type | Description |
|---|---|---|
currentPage | string | Current URL path (e.g., /settings/billing) |
currentFeature | string | Human-readable feature name (e.g., Billing Settings) |
userRole | string | User's role for action filtering (e.g., admin, member) |
userState | string | User's current state (e.g., onboarding, trial, active) |
errorState | object | Current error with code and message |
custom | object | Any additional context data |
Auto-Sync with Routing
Next.js App Router
// components/RouteContextSync.tsx'use client';import { usePillar } from '@pillar-ai/react';import { usePathname } from 'next/navigation';import { useEffect } from 'react';export function RouteContextSync() {const { pillar } = usePillar();const pathname = usePathname();useEffect(() => {pillar?.setContext({ currentPage: pathname });}, [pillar, pathname]);return null;}
Add to your provider:
<PillarProvider productKey="..." publicKey="..."><RouteContextSync />{children} {/* Your app content */}</PillarProvider>
React Router
import { useLocation } from 'react-router-dom';function RouteContextSync() {const { pillar } = usePillar();const location = useLocation();useEffect(() => {pillar?.setContext({ currentPage: location.pathname });}, [pillar, location]);return null;}
Vanilla JavaScript (SPA)
For single-page applications without React:
// Sync context on every navigation (vanilla JS SPA)const pillar = Pillar.getInstance();// Track the current pathlet lastPath = window.location.pathname;// Poll for path changes (for SPAs without popstate)setInterval(() => {if (window.location.pathname !== lastPath) {lastPath = window.location.pathname;pillar?.setContext({ currentPage: lastPath });}}, 300);// Also listen for popstate (back/forward buttons)window.addEventListener('popstate', () => {pillar?.setContext({ currentPage: window.location.pathname });});
Feature-Specific Context
Set context based on what the user is doing:
function BillingPage() {const { pillar } = usePillar();useEffect(() => {pillar?.setContext({currentPage: '/settings/billing',currentFeature: 'Billing Settings',custom: {userPlan: 'pro',hasPaymentMethod: true,},});}, [pillar]);return <BillingSettings />;}
Error Context
Help users troubleshoot errors:
function PaymentForm() {const { pillar } = usePillar();const [error, setError] = useState(null);const handlePaymentError = (err) => {setError(err);// Tell Pillar about the errorpillar?.setContext({errorState: {code: err.code,message: err.message,},});};return (<form onSubmit={handleSubmit}>{error && <ErrorMessage error={error} />}{/* ... */}</form>);}
Now when users ask for help, the AI knows about the error.
User Context
Pass user information for personalized help and action filtering:
function UserContextSync() {const { pillar } = usePillar();const { user } = useAuth();useEffect(() => {if (user && pillar) {pillar.setContext({userRole: user.role,userState: user.subscription?.status,custom: {plan: user.subscription?.plan,},});}}, [pillar, user]);return null;}
Action Filtering with Context
Context enables action filtering based on user attributes. When you define actions with requiredContext, only users matching that context will see those actions suggested.
// Your action definition{name: 'delete_user',description: 'Delete a user from the organization',requiredContext: { userRole: 'admin' },// ...}
// In your app - only admins see the delete_user actionpillar.setContext({ userRole: user.role }); // 'admin' or 'member'
See Actions for more on requiredContext.
Clearing Context
Reset context when needed:
// Clear specific keyspillar?.setContext({errorState: undefined,});// Or set completely new contextpillar?.setContext({currentPage: '/dashboard',});
Best Practices
Keep Context Current
Update context when the user navigates or state changes:
useEffect(() => {pillar?.setContext({ currentPage: pathname });}, [pathname, pillar]);
Include Relevant Details
The more context you provide, the better the AI can help:
pillar?.setContext({currentPage: '/projects/123/settings',currentFeature: 'Project Settings',userRole: 'owner',custom: {projectId: '123',projectName: 'My Project',},});
Handle Auth State
Clear user context on logout:
function handleLogout() {pillar?.setContext({userRole: undefined,userState: undefined,});// Continue logout...}