Provider Setup Pattern
Correct provider hierarchy for TelamonJS apps (AdminShell + React Query)
How to mount the providers and the shell of a TelamonJS app: AppProviders at the root (with the
app's own QueryClient), AdminShell in the admin area's layout. Apps generated by the CLI
already start this way.
File Structure
src/
├── app/
│ ├── layout.tsx # Root: <html> + <body> + AppProviders
│ └── admin/
│ └── layout.tsx # Server Component: auth() + redirect + LayoutProviders
├── components/
│ └── providers/
│ ├── providers.tsx # 'use client': the app's QueryClient + AppProviders
│ └── LayoutProviders.tsx # 'use client': AdminShell + Toaster
├── config/
│ └── menu.ts # Typed MenuItem[] (icons as strings)
└── lib/
├── auth.ts # NextAuth v5 (auth())
└── icons.ts # Project-owned iconRegistryThe library's styles come from @telamonjs/ui/styles and its Tailwind preset from
@telamonjs/ui/tailwind-preset.
1. AppProviders
AppProviders mounts i18n, the theme (next-themes), the NextAuth session, the cache-revalidation
context, Google Maps and a React Query client. Everything it accepts goes through config
(ProvidersConfig): queryClient, queryClientConfig, themeConfig, authConfig, session,
googleMapsApiKey, revalidateAction and i18n (see i18n).
It does not mount a toaster. The library's toasts use sonner
(a peer dependency), so render the Sonner toaster once yourself (see AdminShell)
and call toast from sonner in app code.
It also mounts an instant tooltip: icon-only buttons and links show their aria-label or title
immediately on mouse hover. data-tooltip="off" opts an element out, and data-tooltip-text sets
explicit text, which also applies to buttons with a visible label. An app with its own global
tooltip for icon-only buttons must remove it, otherwise both run.
The root layout stays a Server Component; it only needs <html suppressHydrationWarning> and
<body> around the client providers component of the next section:
import { Providers } from '@/components/providers/providers'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang='en' suppressHydrationWarning>
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}2. The app's QueryClient
Every module built on CrudConfig reads and writes through React Query. An app that has its own
QueryClient (global error toasts, 401 redirect) passes it to AppProviders in
config.queryClient and keeps its own QueryClientProvider outside, with the same client.
Neither half is enough on its own:
- Only the outer provider: with the published package there is a single copy of react-query,
and the client
AppProviderscreates internally shadows the app's for the whole tree. The app's globalonErrorhandlers and the invalidations made on its client silently stop working. - Only
config.queryClient: the app's client also serves the library's queries and mutations, which already handle their own errors. Without themetacheck below, users see each error twice.
'use client'
import { useState } from 'react'
import {
MutationCache,
QueryCache,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { AppProviders } from '@telamonjs/ui'
import { revalidatePathAction } from '@telamonjs/ui/server'
import { handleApiError } from '@/lib/api/error-handler'
export function Providers({ children }: { children: React.ReactNode }) {
// useState, never module scope: a module-level client would be shared
// across requests (and users) on the server.
const [queryClient] = useState(
() =>
new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
if (query.meta?.skipErrorToast) return
handleApiError(error)
},
}),
mutationCache: new MutationCache({
onError: (error, _variables, _context, mutation) => {
if (mutation.meta?.skipErrorToast) return
handleApiError(error)
},
}),
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1 } },
})
)
// Same client in both: AppProviders uses it for the whole tree. The outer
// provider matters when the library is linked (see /docs/troubleshooting).
return (
<QueryClientProvider client={queryClient}>
<AppProviders config={{ queryClient, revalidateAction: revalidatePathAction }}>
{children}
</AppProviders>
</QueryClientProvider>
)
}meta.skipErrorToastcontract: every query and mutation the library runs (CRUD, lists, the queue dashboard) carriesmeta: { skipErrorToast: true }, because the library already shows its own error (a toast for mutations, an error state with a retry button for lists). The app's global handler must honor that key. The app can set the same key on its own queries that handle errors locally.- With
config.queryClient,config.queryClientConfigis ignored. - A client from another copy of react-query (a linked library) is ignored with a development-only warning. See Troubleshooting.
- Apps that mount providers by hand, without
AppProviders, can use the library'sQueryClientProvider(it acceptsclientorconfig).
Single React Query instance
Always import QueryClient, QueryCache and MutationCache from @tanstack/react-query
(@telamonjs/ui never re-exports them) and configure
experimental.optimizePackageImports: ['@telamonjs/ui'] in next.config. Two instances of the
react-query module cause "No QueryClient set": see
Troubleshooting.
3. SystemConfigProvider (optional)
An app-wide configuration context read with useSystemConfig() ({ config, updateConfig }).
AdminShell does not depend on it; use it only when the app needs to read this configuration in
several places. SystemConfig has six required blocks:
| Block | Fields |
|---|---|
identity | name, description, version, logo?, favicon? |
layout | defaultSidebarState ('expanded' | 'compact' | 'hidden'), showBreadcrumb, showSearch, showNotifications, maxContentWidth? |
menu | items: MenuItem[], showIcons, showBadges, allowCollapse |
theme | primaryColor, mode ('light' | 'dark' | 'system'), customCSS? |
auth | enabled, redirectPath, sessionProvider ('nextauth' | 'custom') |
links | home, support?, documentation?, github? |
import { SystemConfigProvider } from '@telamonjs/ui'
import { systemConfig } from '@/config/system-config'
<SystemConfigProvider config={systemConfig}>{children}</SystemConfigProvider>4. AdminShell
Composes ModernSidebar + CommandPalette (Cmd+K) + ResponsiveBreadcrumb + header. The admin
layout is a Server Component: it reads the session, redirects when there is none, and passes the
session down as a prop — AdminShell itself is 'use client'.
import { redirect } from 'next/navigation'
import { auth } from '@/lib/auth'
import { LayoutProviders } from '@/components/providers/LayoutProviders'
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await auth()
if (!session) redirect('/sign-in')
return <LayoutProviders session={session}>{children}</LayoutProviders>
}'use client'
import { useRouter } from 'next/navigation'
import type { Session } from 'next-auth'
import { AdminShell, Sonner as Toaster } from '@telamonjs/ui'
import { menuConfig } from '@/config/menu'
export function LayoutProviders({
children,
session,
}: {
children: React.ReactNode
session: Session
}) {
const router = useRouter()
return (
<>
<AdminShell
menuConfig={menuConfig}
session={{
user: {
name: session.user?.name ?? undefined,
email: session.user?.email ?? undefined,
},
}}
systemName='My Admin'
logoUrl='/logo.png'
compactLogoUrl='/icon-compact.png'
onSignOut={() => router.push('/sign-out')}
>
{children}
</AdminShell>
<Toaster />
</>
)
}Main props: menuConfig, session?, systemName?, logoUrl?/compactLogoUrl? (plus
logoHeight?, logoMaxWidth? and their compact variants), onSignOut?, onStopImpersonation?,
showImpersonationBanner?, headerActions?, commandActions?, breadcrumbProps?,
profileHref?, localeSwitcher?. See AdminShell for the full list.
Permissions (optional)
To gate menus, lists and actions with the session's permissions, wrap the shell in
PermissionsProvider with your checker. It lives here, not in AppProviders, because the
checker usually reads the session through a hook that only works inside SessionProvider:
<PermissionsProvider can={can}>
<AdminShell menuConfig={menuConfig}>{children}</AdminShell>
</PermissionsProvider>See One checker for the whole app.
Provider Hierarchy
QueryClientProvider (the app's QueryClient)
└── AppProviders (i18n, theme, session, same QueryClient, maps)
└── app/admin/layout.tsx (Server Component: session + redirect)
└── PermissionsProvider (optional: the session's `can`)
└── AdminShell (ModernSidebar + CommandPalette + Breadcrumb, 'use client')
└── {children}Typed menu (menuConfig)
AdminShell receives a typed menu with icons passed as strings, resolved via
getIcon/setIconResolver — never import the Lucide component directly in the menu.
import type { MenuItem } from '@telamonjs/ui'
export const menuConfig: MenuItem[] = [
{
id: 'dashboard',
type: 'single',
title: 'Dashboard',
href: '/admin',
icon: 'LayoutDashboard', // STRING — resolved via getIcon()
},
{
id: 'admin-group',
type: 'group',
title: 'Administration',
icon: 'Settings',
children: [
{ id: 'users', type: 'single', title: 'Users', href: '/admin/users', icon: 'Users' },
],
},
]Icon Resolver (setIconResolver)
The iconRegistry (name → lucide component) belongs to the project, not to @telamonjs/ui; the
library only keeps a small curated fallback map. Domain-specific icons live in the project's
registry. Register a resolver once at boot (client side), for example at the top of the providers
component:
import { Home, Users, Settings, Receipt, type LucideIcon } from 'lucide-react'
export const iconRegistry: Record<string, LucideIcon> = {
Home,
Users,
Settings,
Receipt,
// add entries here when using a new icon in a menu/tab/header
}'use client'
import { setIconResolver } from '@telamonjs/ui'
import { iconRegistry } from '@/lib/icons'
// getIcon now looks up: the project's resolver → the library's curated map → Circle
setIconResolver(name => iconRegistry[name])The same strings work everywhere an icon is accepted — menu items, TabItem.icon,
AdminHeader.icon and dashboard items all take string | IconComponent:
const tabs: TabItem[] = [
{ value: 'usage', label: 'Usage', icon: 'Receipt', content: <UsageTab /> },
]
<AdminHeader title='Billing' icon='Receipt' />Prefer strings over passing the Lucide component (icon: Home as IconComponent): strings work the
same everywhere, while a component can fail type-check when the library is linked (see
Troubleshooting).
setIconResolver(null) clears the resolver (useful in tests).
Best Practices
- Server session. Fetch the session on the server and pass it down as a prop — never call
useSession()inside a client component that rendersAdminShell: it flashes content and causes hydration errors. - One
QueryClientper app, created withuseStatein a client component and passed inconfig.queryClient(see above). - Separate config files:
menu.tsfor navigation,auth.tsfor authentication, andsystem-config.tsif you useSystemConfigProvider. - Menu icons as strings, resolved through the project's
iconRegistry+setIconResolver.
Troubleshooting
Hydration Errors
Symptom: "Hydration failed" errors in console
Solution: Set suppressHydrationWarning on <html> — next-themes changes its class before
hydration.
Theme Not Persisting
Symptom: The theme resets on page reload.
Solution: AppProviders uses next-themes, which persists to localStorage on its own. Make
sure suppressHydrationWarning is set and there is no second theme provider.
Global error handlers never fire
Symptom: The app's QueryCache/MutationCache onError (toast, 401 redirect) works in
development but not in production.
Solution: The app's client is not passed to AppProviders, so the library's internal client
shadows it. Pass it in config.queryClient (see The app's QueryClient).
"No QueryClient set"
Two copies of react-query: see Troubleshooting.
Menu Not Showing
Symptom: Sidebar empty or menu items missing
Solution: Verify menuConfig is passed to AdminShell, has the MenuItem[] shape
(type: 'single' | 'group' | 'separator') and unique ids.
Icon shows as a circle
Symptom: A menu/tab/header icon renders as a generic circle (Circle).
Solution: The icon name isn't registered in the project's iconRegistry — add it there,
not in @telamonjs/ui.
Session Not Available
Symptom: session is null or undefined.
Solution: Make sure NextAuth is configured and the session is read on the server
(const session = await auth()) in the admin layout.
Related Patterns
- i18n - Locale, messages and
config.i18n - Admin Module Structure - Where each file of a CRUD module lives
- Dashboard Pattern - Dashboard pages inside the shell
Result
Correct provider hierarchy, theme persistence, a single React Query client shared by the app and the library, type-safe menu, server-side session.