Custom Context Helpers
Creating and using custom context helpers
Custom context helpers let you automatically include application-specific data with every message. A helper is just a function that returns a value (or null/undefined to skip). The object key you provide becomes the context name in messages.
Defining Helpers
You can define helpers as simple functions:
// Reusable helpers
const sessionHelper = async () => ({
sessionId: getSessionId(),
startTime: getSessionStartTime(),
user: await getCurrentUser(),
});
const environmentHelper = async () => ({
env: process.env.NODE_ENV,
version: process.env.NEXT_PUBLIC_APP_VERSION,
feature_flags: await getFeatureFlags(),
});
// Use in TamboProvider
<TamboProvider
contextHelpers={{
session: sessionHelper, // Key becomes context name
environment: environmentHelper,
}}
/>;
Inline Custom Helpers
Define helpers inline where you configure the provider:
<TamboProvider
contextHelpers={{
deviceInfo: async () => ({
userAgent: navigator.userAgent,
platform: navigator.platform,
screenResolution: {
width: window.screen.width,
height: window.screen.height,
},
}),
}}
/>
Overriding Prebuilt Helpers
Replace a prebuilt helper by using the same key:
<TamboProvider
contextHelpers={{
// Override the built-in userTime helper
userTime: async () => ({
formattedTime: new Date().toLocaleString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
}),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}),
}}
/>
Async vs Sync
Helpers can be synchronous or asynchronous:
// Synchronous
const syncHelper = () => ({
theme: getTheme(),
language: getLanguage(),
});
// Asynchronous
const asyncHelper = async () => ({
user: await fetchUser(),
permissions: await fetchPermissions(),
});
Tip: Return null/undefined from a helper to skip including it in a particular environment or condition (e.g., return null for browser-only helpers on the server).