Projects
PreviousNext

Next.js Shadcn Dashboard Data Fetching: Server Actions vs Route Handlers vs BFF

How to fetch data in a Next.js shadcn admin dashboard: server actions, route handlers, the BFF (backend for frontend) pattern or an external API. How each works in Shadcn Dashboard by Kiranism, how auth flows, and the SSR prefetch trap to avoid.

K I R A N
K I R A N

Short answer: A Next.js shadcn admin dashboard can fetch its data with four patterns:

  1. Server actions + ORM: full stack, Next.js talks to the database directly.
  2. Route handlers + ORM: full stack, through your own /api endpoints.
  3. BFF (backend for frontend): Next.js route handlers proxy to a separate backend like Laravel, Django, Go or NestJS.
  4. Direct external API: the frontend calls your backend straight from the browser.

Pick 1 if Next.js owns the database. Pick 3 if a separate backend team owns the API. Pick 2 or 4 only for the specific reasons below.

All four are built into Shadcn Dashboard by Kiranism: every feature's service.ts lists them at the top, and the tables and forms don't change no matter which one you pick. This post explains how each pattern works, how auth flows through it, and one server-rendering trap that silently breaks two of them.


The four patterns at a glance

PatternWho talks to the databaseWhere auth is checkedServer prefetch (SSR)Best for
1. Server actions + ORMNext.jsInside every actionWorks as isFull-stack apps where Next.js owns the data
2. Route handlers + ORMNext.jsInside every route handlerNeeds a prefetch overrideEndpoints shared with a mobile app or webhooks
3. BFF proxyYour external backendRoute handler + backend verifies tokenNeeds a prefetch overrideSeparate backend team, keeping tokens off the browser
4. Direct external APIYour external backendYour backend onlyNeeds cookie forwarding, or skip itExisting public APIs, static frontends

The default in the starter is a fifth option, mock data: in-memory fake stores, so every page works before you have a backend.


The one rule: only service.ts changes

Each feature has the same data layer:

features/products/api/
├── types.ts     # Data shapes
├── service.ts   # How to talk to the backend. The only file you change.
└── queries.ts   # TanStack Query options: cache keys + fetchers

Components call queries.ts, and queries.ts calls service.ts. Switching from mock data to any of the four patterns means rewriting service.ts (plus a route handler for patterns 2 and 3). Tables, forms, cache keys and invalidation stay the same.


The SSR trap: your service runs in two places

This is the part most guides skip, and it's the reason patterns 2, 3 and 4 need extra care.

The starter follows the official TanStack Query SSR pattern. A Server Component prefetches the data, HydrationBoundary sends it to the browser, and useSuspenseQuery picks it up there. That means the same service.ts function runs on the server during the prefetch, and in the browser on every refetch and mutation.

Two things that work in the browser fail on the server:

  • Relative URLs. fetch('/api/products') is fine in a browser. On the server, Node throws Failed to parse URL from /api/products, because there's no current page to resolve it against.
  • Browser cookies. A server-side fetch doesn't automatically carry the user's cookies, so a cookie-authenticated API sees an anonymous request.

The prefetch is wrapped in .catch(noop), so these failures are silent. The page still loads, and the browser fetches the data, but you lose server rendering and users see a loading skeleton on every visit. If your table flashes a skeleton after you connect a backend, this is almost always why.

The fix is the same in every pattern: override queryFn at the prefetch site so the server uses a server-side path. The cache key stays the same, so the browser still hydrates from it. TanStack's own Next.js optimistic updates example uses this technique.


Pattern 1: Server actions + ORM (full stack)

How it works: add 'use server' to the top of service.ts and call your ORM (Drizzle, Prisma or Supabase) directly in each function. Every export becomes a server action.

// features/products/api/service.ts
'use server';
 
export async function getProducts(filters: ProductFilters): Promise<ProductsResponse> {
  await requireUser(); // check auth in every action
  // ...Drizzle or Prisma query
}

Why it's the simplest: server actions run on the server both when the Server Component calls them and when the browser does, so the SSR trap doesn't apply. No API routes, no URLs, no cookie forwarding.

Auth: a server action is a public HTTP endpoint, even if only your UI calls it. Protecting the page doesn't protect the action, so check the session at the top of each one.

Watch out for: server actions are designed for mutations and run one at a time per client. They're fine for dashboard reads at normal traffic, but if you need parallel or cacheable GET requests, use pattern 2.

I wrote a full walkthrough of this pattern, tested against Postgres: How to Connect Postgres to a Next.js Admin Dashboard with Drizzle ORM.


Pattern 2: Route handlers + ORM

How it works: service.ts calls your own /api routes through the starter's apiClient, and the route handlers in src/app/api/ query the database.

// lib/query-string.ts (used by patterns 2, 3 and 4)
export function toQueryString(params: Record<string, unknown>) {
  return new URLSearchParams(
    Object.entries(params)
      .filter(([, value]) => value !== undefined)
      .map(([key, value]) => [key, String(value)])
  ).toString();
}
// features/products/api/service.ts
import { apiClient } from '@/lib/api-client';
import { toQueryString } from '@/lib/query-string';
 
export async function getProducts(filters: ProductFilters): Promise<ProductsResponse> {
  return apiClient<ProductsResponse>(`/products?${toQueryString(filters)}`);
}

Put the database query in one server-only function, so the route handler and the prefetch share it:

// features/products/server/products.ts
import 'server-only';
 
export async function listProducts(filters: ProductFilters): Promise<ProductsResponse> {
  // your ORM query
}

The route handlers already check auth with Clerk. Replace their mock calls with listProducts(). Then fix the SSR trap by overriding the prefetch, since apiClient uses a relative /api URL:

// features/products/components/product-listing.tsx
void queryClient
  .query({ ...productQueries.list(filters), queryFn: () => listProducts(filters) })
  .catch(noop);

The server queries the database directly, without an HTTP round trip to itself. The browser keeps using /api/products.

Pick it when: something besides your dashboard calls the same endpoints, such as a mobile app, a partner integration or webhooks, or you want plain GET requests you can cache and inspect in the network tab.


Pattern 3: BFF, a backend for frontend

How it works: your real API is a separate service (Laravel, Django, Go, NestJS, Rails). Next.js route handlers act as a thin proxy in front of it. The browser only ever talks to your Next.js app, and the backend URL and tokens stay on the server.

service.ts looks exactly like pattern 2: it calls /api/products through apiClient. The difference is in the route handler, which forwards the request with a server-side token:

// lib/backend.ts
import 'server-only';
import { auth } from '@clerk/nextjs/server';
 
export async function backendFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const { getToken } = await auth();
  const res = await fetch(`${process.env.BACKEND_URL}${path}`, {
    ...init,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${await getToken()}`,
      ...init?.headers
    },
    cache: 'no-store'
  });
  if (!res.ok) throw new Error(`Backend error: ${res.status}`);
  return res.json() as Promise<T>;
}
// app/api/products/route.ts
export async function GET(request: NextRequest) {
  const { userId } = await auth();
  if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
 
  const data = await backendFetch<ProductsResponse>(`/products?${request.nextUrl.searchParams}`);
  return NextResponse.json(data);
}

Your backend verifies the Clerk session token (a signed JWT) with Clerk's backend SDK or its public keys. For the server prefetch, skip the proxy and call the backend directly with the same helper:

void queryClient
  .query({
    ...productQueries.list(filters),
    queryFn: () => backendFetch<ProductsResponse>(`/products?${toQueryString(filters)}`)
  })
  .catch(noop);

Why teams pick it:

  • No CORS. The browser only calls your own domain.
  • Secrets stay server-side. The backend URL, API keys and service tokens never ship to the browser.
  • Shape data for the UI. The BFF can merge two backend calls into one response, rename fields to match your types, or hide internal fields.
  • Independent teams. The backend team keeps its API. The frontend team owns the BFF layer.

Trade-off: one extra network hop per request, and one more layer to maintain. Keep the BFF thin: proxy, auth and light shaping, no business logic.


Pattern 4: Direct external API (frontend only)

How it works: service.ts calls your backend's absolute URL straight from the browser. Next.js is purely a frontend.

// features/products/api/service.ts
export async function getProducts(filters: ProductFilters): Promise<ProductsResponse> {
  const res = await fetch(`https://api.example.com/products?${toQueryString(filters)}`, {
    credentials: 'include' // send the API's session cookie
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

What it needs:

  • CORS on your backend, allowing your dashboard's origin with credentials.
  • Cookie or token auth that the browser can send. With cookies, the API and the dashboard usually need to share a parent domain (app.example.com and api.example.com).
  • A decision on SSR. The server prefetch has no browser cookies. Either forward them at the prefetch site, as the starter's AGENTS.md describes, or remove the prefetch for that page and let the browser load the data. Never import next/headers inside service.ts, because client components import that file too.

Pick it when: you already have a mature public API, you're migrating an existing SPA, or you plan to export the dashboard as a static site.

Trade-off: you give up most of what Next.js does on the server, and your API's URL and auth flow are visible in the browser.


What about the TanStack Start edition?

The TanStack Start edition collapses these choices into one primitive. Every service.ts export is a server function: createServerFn() with a Zod validator and auth middleware. The handler always runs on the server, whether a route loader or the browser calls it.

  • Query your ORM in the handler, and you have pattern 1.
  • fetch() your external backend in the handler, and you have pattern 3, a BFF, with no separate route handlers.

Because the handler never runs in the browser, the SSR trap above doesn't exist there. That's one of the real advantages I covered in Next.js vs TanStack Start for admin dashboards.


Which pattern should you choose?

  • You're building the whole product in Next.js, with your own database: pattern 1, server actions + ORM
  • A mobile app or third party will call the same endpoints: pattern 2, route handlers + ORM
  • A separate backend team owns the API, or the backend isn't JavaScript: pattern 3, BFF
  • You have a public API with CORS already, or need a static export: pattern 4, direct external API
  • You're still designing the backend: stay on mock data. The tables and forms won't change when you switch.

FAQ

What is the BFF pattern in Next.js?

BFF stands for backend for frontend. Next.js route handlers sit between the browser and your real backend. The browser calls your Next.js app, and the route handler forwards the request to the backend with server-side credentials. It removes CORS issues, keeps tokens and internal URLs off the browser, and lets you shape responses for the UI.

Should I use server actions or route handlers for a dashboard?

Use server actions when only your own UI calls the code and Next.js owns the database: they're the least code and work with SSR out of the box. Use route handlers when other clients (mobile apps, webhooks, partners) need the same endpoints, or when you want cacheable GET requests.

Can I use Next.js as a frontend for a Laravel, Django or Go backend?

Yes. Use the BFF pattern if you want tokens and the backend URL to stay on the server, or call the API directly from the browser if it already supports CORS and cookie or token auth. In Shadcn Dashboard by Kiranism, either way only changes each feature's service.ts and, for a BFF, the route handlers.

Should a Server Component fetch my own Next.js API routes?

No. Calling your own route handler from the server adds an HTTP round trip, and a relative URL like /api/products fails on the server. Call the shared data function directly instead, and keep the route handler for browser and external clients.

Why does my table show a loading skeleton even though I prefetch on the server?

The server prefetch most likely failed silently. Common causes: a relative fetch('/api/...') URL, which Node can't resolve, or a cookie-authenticated API that receives no cookies on the server. Override queryFn at the prefetch site with a server-side call, and keep the same query key.

Where do tRPC and GraphQL fit?

They're variations of these patterns, not new ones. tRPC is a typed version of pattern 1 or 2: procedures run on your Next.js server. GraphQL is usually pattern 3 or 4: a separate server you call through a BFF or from the browser. Either way, the calls live in service.ts.


Wrapping up

There's no single right backend for a dashboard. What makes the choice cheap is a data layer where only one file per feature knows which pattern you picked. That's how I built Shadcn Dashboard by Kiranism, and a GitHub star helps more people find it.

Next step: connect Postgres with Drizzle ORM, the full walkthrough of pattern 1.