perf(layout): dashboard layout in two waves, nav flags as one RPC, local JWT verification (#1946)
The dashboard layout runs on every hard load, hard refresh, company switch and the 16 router.refresh() sites, and loading.tsx cannot paint until it resolves. It cost ~20 network calls in 4 sequential waves: a third getUser() round trip to Supabase Auth (after the proxy's and the route guard's), the company resolution, then 16 reads including four limit-1 probes whose only job is to decide whether to render the Webshop and Körjournal nav rows, and an entitlements read that itself ran two waves. - lib/auth/claims.ts: claimsPinned/userFromClaims extracted from require-auth.ts (unchanged) so the dashboard request context shares the exact pinning + mapping. getDashboardAuthContext verifies the JWT locally and falls back to getUser() only when claims are missing, unpinned or unverifiable: the proxy already performed the per-request revocation check before the layout runs (same semantics approved for routes on 2026-07-23). - Wave 1 (user-keyed, parallel with the company resolution): team membership, profile, user preferences and the memberships join, which now also supplies the active company's row and role, so the separate companies and company_members reads are gone. - Wave 2 (company-keyed): settings, agent profile, the switcher's settings names, entitlements in ONE wave (getCompanyEntitlements takes the team_id the join already carries and runs the grants read alongside config + subscription), and get_dashboard_nav_flags(). - supabase/migrations/20260826120000_get_dashboard_nav_flags.sql: SECURITY INVOKER, STABLE, EXECUTE for authenticated only; RLS applies inside. lib/dashboard/nav-flags.ts wraps it with the pre-RPC four-probe fallback on PGRST202/42883/42501 (self-hosted not yet migrated, deploy ordering) and degrades to hidden rows on any other error. - tests/pg/dashboard-nav-flags-rpc.pg.test.ts (6): fresh company, active vs pending WooCommerce, active Shopify, mileage trips, RLS for a member of another company, EXECUTE grants. Unit tests for the wrapper (RPC row, single-object payload, each fallback code, other errors) and for the entitlements teamId option. ~20 calls / 4 waves -> ~12 calls / 2 waves, 0 auth network calls. Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Jakob Wennberg
Claude Fable 5
parent
1a41119682
commit
4ac7b45c8a
+39
-56
@@ -16,6 +16,7 @@ import { getExtensionNavItems } from '@/lib/extensions/sectors'
|
||||
import { CompanyProvider } from '@/contexts/CompanyContext'
|
||||
import { ReferenceDataSeed } from '@/components/providers/ReferenceDataSeed'
|
||||
import { getCompanyEntitlements } from '@/lib/entitlements/has-capability'
|
||||
import { getDashboardNavFlags } from '@/lib/dashboard/nav-flags'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import type { AccountingFramework, EntityType, CompanyRole, Team } from '@/types'
|
||||
import {
|
||||
@@ -69,7 +70,17 @@ export default async function DashboardLayout({
|
||||
// Team membership (with the team row embedded) only depends on user.id,
|
||||
// so it resolves in parallel, this layout is on the critical path of
|
||||
// every dashboard page, so sequential round-trips are wall-clock time.
|
||||
const [companyId, headerStore, { data: teamMembership }] = await Promise.all([
|
||||
// Wave 1: everything keyed on the user alone runs alongside the company
|
||||
// resolution. The memberships join carries the active company's row and
|
||||
// role too, so wave 2 no longer re-reads companies / company_members.
|
||||
const [
|
||||
companyId,
|
||||
headerStore,
|
||||
{ data: teamMembership },
|
||||
{ data: userProfile },
|
||||
{ data: userPrefs },
|
||||
{ data: allMemberships },
|
||||
] = await Promise.all([
|
||||
getDashboardCompanyId(),
|
||||
// Read the pathname forwarded by middleware so we can branch on it.
|
||||
headers(),
|
||||
@@ -79,6 +90,15 @@ export default async function DashboardLayout({
|
||||
.eq('user_id', user.id)
|
||||
.limit(1)
|
||||
.maybeSingle(),
|
||||
// The signed-in user's profile, shown in the bottom-left account
|
||||
// popover (full_name + initial) so it's clear which user is logged
|
||||
// in, distinct from the active company shown at the top.
|
||||
supabase.from('profiles').select('full_name').eq('id', user.id).maybeSingle(),
|
||||
// Per-user UI state (nav collapse/fold state), server-rendered so the
|
||||
// sidebar width is right on first paint, plus the hide-assistant-FAB
|
||||
// preference (Inställningar → Assistenten).
|
||||
supabase.from('user_preferences').select('ui_state, hide_assistant_fab').eq('user_id', user.id).maybeSingle(),
|
||||
supabase.from('company_members').select('company_id, role, companies:company_id(id, name, org_number, entity_type, accounting_framework, created_by, team_id, archived_at, created_at, updated_at)').eq('user_id', user.id),
|
||||
])
|
||||
|
||||
const pathname = headerStore.get('x-pathname') ?? ''
|
||||
@@ -140,78 +160,39 @@ export default async function DashboardLayout({
|
||||
)
|
||||
}
|
||||
|
||||
// Fetch company + membership for context provider, together with the
|
||||
// nav/badge data, none of these depend on each other, only on
|
||||
// companyId/user.id, so one round-trip batch instead of two. The rare
|
||||
// stale-cookie early return below wastes the extra reads; that's cheaper
|
||||
// than serializing two batches on every dashboard render.
|
||||
// The active company's row and role come from the memberships join above
|
||||
// (a company the user is not a member of resolves to null, same as the old
|
||||
// .single() reads did).
|
||||
const activeMembership = (allMemberships || []).find((m) => m.company_id === companyId) ?? null
|
||||
const companyRow = (activeMembership?.companies as unknown as import('@/types').Company | null) ?? null
|
||||
const memberRow = activeMembership ? { role: activeMembership.role } : null
|
||||
|
||||
// Wave 2: everything keyed on the company. Nav badge counts are NOT fetched
|
||||
// here: DashboardNav loads them client-side after mount
|
||||
// (lib/hooks/use-worklist-badges). The four nav-visibility probes
|
||||
// (webshop connections/orders, mileage trips) collapsed into one RPC.
|
||||
const [
|
||||
{ data: companyRow },
|
||||
{ data: memberRow },
|
||||
{ data: allMemberships },
|
||||
{ data: settings, error: settingsError },
|
||||
agentProfileIdentity,
|
||||
{ data: userProfile },
|
||||
entitlements,
|
||||
{ data: allSettingsNames },
|
||||
{ data: userPrefs },
|
||||
hasWebshop,
|
||||
hasMileageTrips,
|
||||
navFlags,
|
||||
{ data: seedFiscalPeriods },
|
||||
{ data: seedCashAccounts },
|
||||
] = await Promise.all([
|
||||
supabase.from('companies').select('*').eq('id', companyId).single(),
|
||||
supabase.from('company_members').select('role').eq('company_id', companyId).eq('user_id', user.id).single(),
|
||||
supabase.from('company_members').select('company_id, role, companies:company_id(id, name, org_number, entity_type, accounting_framework, created_by, team_id, archived_at, created_at, updated_at)').eq('user_id', user.id),
|
||||
getDashboardSettings(),
|
||||
// Nav badge counts (unbooked transactions, pending operations) are NOT
|
||||
// fetched here anymore: DashboardNav loads them client-side after mount
|
||||
// (lib/hooks/use-worklist-badges) so two head-count queries stop blocking
|
||||
// first paint on every dashboard navigation.
|
||||
// Agent identity, name + avatar, surfaced on the FAB and chat
|
||||
// surfaces. Null when no agent_profile exists yet (banner CTA path).
|
||||
getResolvedDashboardAgentProfile(),
|
||||
// The signed-in user's profile, shown in the bottom-left account
|
||||
// popover (full_name + initial) so it's clear which user is logged
|
||||
// in, distinct from the active company shown at the top.
|
||||
supabase.from('profiles').select('full_name').eq('id', user.id).maybeSingle(),
|
||||
getCompanyEntitlements(supabase, companyId),
|
||||
// teamId comes from the membership join, so the entitlements read is one
|
||||
// wave (grants in parallel with config + subscription).
|
||||
getCompanyEntitlements(supabase, companyId, { teamId: companyRow?.team_id ?? null }),
|
||||
// Current display names for ALL the user's companies (the switcher list).
|
||||
// RLS scopes company_settings SELECT to user_company_ids(), so this bare
|
||||
// select returns exactly the caller's companies, letting non-active rows
|
||||
// show company_settings.company_name instead of the frozen companies.name.
|
||||
supabase.from('company_settings').select('company_id, company_name'),
|
||||
// Per-user UI state (nav collapse/fold state), server-rendered so the
|
||||
// sidebar width is right on first paint, plus the hide-assistant-FAB
|
||||
// preference (Inställningar → Assistenten). Batched here so it costs no
|
||||
// extra round-trip on the dashboard critical path.
|
||||
supabase.from('user_preferences').select('ui_state, hide_assistant_fab').eq('user_id', user.id).maybeSingle(),
|
||||
// Whether the company has a webshop hooked up: an ACTIVE WooCommerce or
|
||||
// Shopify connection, or already-imported webshop_orders rows (a
|
||||
// disconnected store's orders are accounting underlag and must stay
|
||||
// reachable). Three indexed limit-1 selects, parallel with the batch;
|
||||
// accepted cost on the first-paint path (gates a nav destination, unlike
|
||||
// the badge counts that moved client-side above).
|
||||
Promise.all([
|
||||
supabase.from('woocommerce_connections').select('id').eq('company_id', companyId).eq('status', 'active').limit(1),
|
||||
supabase.from('shopify_connections').select('id').eq('company_id', companyId).eq('status', 'active').limit(1),
|
||||
supabase.from('webshop_orders').select('id').eq('company_id', companyId).limit(1),
|
||||
]).then(
|
||||
([woo, shopify, orders]) =>
|
||||
(woo.data?.length ?? 0) > 0 ||
|
||||
(shopify.data?.length ?? 0) > 0 ||
|
||||
(orders.data?.length ?? 0) > 0,
|
||||
),
|
||||
// Whether the company already has mileage trips: OR-ed with the
|
||||
// mileage_enabled settings toggle below so trips created via API/MCP can
|
||||
// never be invisible underlag even if nobody flipped the toggle. Indexed
|
||||
// limit-1 select, same accepted first-paint cost as the webshop gate.
|
||||
supabase
|
||||
.from('mileage_trips')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.limit(1)
|
||||
.then((trips) => (trips.data?.length ?? 0) > 0),
|
||||
getDashboardNavFlags(supabase, companyId),
|
||||
// Reference-data seed (lib/reference-data/seed.ts): the two small lists
|
||||
// that gate almost every form, fetched once here so the first picker a
|
||||
// user opens renders populated with zero client round trips. Same
|
||||
@@ -230,6 +211,8 @@ export default async function DashboardLayout({
|
||||
.order('is_primary', { ascending: false })
|
||||
.order('ledger_account', { ascending: true }),
|
||||
])
|
||||
const hasWebshop = navFlags.hasWebshop
|
||||
const hasMileageTrips = navFlags.hasMileageTrips
|
||||
|
||||
// company_id -> current display name for every company the user belongs to.
|
||||
const nameByCompany = new Map(
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'server-only'
|
||||
|
||||
import { cache } from 'react'
|
||||
import type { User } from '@supabase/supabase-js'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { claimsPinned, userFromClaims } from '@/lib/auth/claims'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
|
||||
|
||||
@@ -11,9 +13,27 @@ import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
|
||||
*/
|
||||
export const getDashboardAuthContext = cache(async () => {
|
||||
const supabase = await createClient()
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
// Local JWT verification first (same pinning + mapping as requireAuth,
|
||||
// lib/auth/claims.ts): the proxy already performed the per-request
|
||||
// revocation check with getUser() before this layout runs, so a second
|
||||
// network round trip to Supabase Auth on every hard load, refresh and
|
||||
// router.refresh() bought nothing. getUser() stays as the authoritative
|
||||
// fallback when claims are missing, unpinned or unverifiable.
|
||||
let user: User | null = null
|
||||
if (typeof supabase.auth.getClaims === 'function') {
|
||||
try {
|
||||
const { data } = await supabase.auth.getClaims()
|
||||
if (data?.claims?.sub && claimsPinned(data.claims)) user = userFromClaims(data.claims)
|
||||
} catch {
|
||||
// Fall through to the network check.
|
||||
}
|
||||
}
|
||||
if (!user) {
|
||||
const {
|
||||
data: { user: fetched },
|
||||
} = await supabase.auth.getUser()
|
||||
user = fetched
|
||||
}
|
||||
|
||||
return { supabase, user }
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user