Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 72 ยท Projects

Project: An Admin Dashboard

Build an admin dashboard in Next.js: nested layouts, URL-driven filters and sorting, a paginated table, Suspense streaming and loading skeletons.

Dashboards are where the App Router earns its keep. A dashboard has a stable frame (sidebar, header), several independent panels that load at different speeds, and tables that people filter and sort all day. Next.js has a ready answer for each: nested layouts for the frame, Suspense for panels that stream in, and search params for table state that lives in the URL.

In this project we plan an admin dashboard with an overview page and an orders table. You will see the real file structure and code, and you will run two stand-ins in your browser: a table driven by the URL, and a page whose panels arrive one by one behind skeletons. The lesson ties together Pages and Layouts, Search Params and Navigation Hooks, Streaming with Suspense and loading.tsx, error.tsx and not-found.tsx.

Real or stand-in? The Next.js code is real and read-only, because this site cannot run a Next.js server. The two live examples are React 19 stand-ins. The URL state uses the # part of the address (the sandbox has no real routing), and the "server data" is a function with a delay. The ideas are the same: the URL is the source of truth for the table, and each panel suspends on its own.

What we are building

Three layers of the dashboard

Layout Sidebar and header that never reload.
Panels Each one loads and streams on its own.
URL state Filters, sort and page live in the address.

The URL is the single source of truth for the table.

1 / 2

The file structure

TEXT
app/
  layout.tsx                  # root: html, body
  dashboard/
    layout.tsx                # sidebar + header, shared by every dashboard page
    page.tsx                  # overview with streaming panels
    loading.tsx               # skeleton for the whole segment
    orders/
      page.tsx                # filtered, sorted, paginated table
      loading.tsx             # table skeleton
lib/
  data.ts                     # server-only data functions
components/
  stat-cards.tsx
  orders-table.tsx
  skeletons.tsx

The dashboard/layout.tsx file wraps every page below it. When you move from "Overview" to "Orders", the sidebar is not re-rendered or remounted: only the page part changes, so scroll position and any state in the sidebar are kept.

TSX
// app/dashboard/layout.tsx
import Link from 'next/link';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  return (
    <div className="grid min-h-screen grid-cols-[14rem_1fr]">
      <aside className="border-r p-4">
        <nav className="flex flex-col gap-2">
          <Link href="/dashboard">Overview</Link>
          <Link href="/dashboard/orders">Orders</Link>
        </nav>
      </aside>
      <section className="p-6">{children}</section>
    </div>
  );
}

For a real app you would add the active-link highlight with usePathname in a small Client Component, as described in Linking and Navigation. Keep that component tiny, so the rest of the layout stays a Server Component.

The orders table: state lives in the URL

A table needs a filter, a search box, sorting and pagination. The tempting design is a Client Component with useState for each. The better design is to put all of it in the URL: /dashboard/orders?status=paid&sort=amount-desc&page=2. Then the page is a Server Component that reads searchParams, queries only the rows it needs, and renders the table. Refreshing, sharing a link and using the back button all work for free.

TSX
// app/dashboard/orders/page.tsx
import Link from 'next/link';
import { getOrders } from '@/lib/data';

type Props = {
  searchParams: Promise<{ status?: string; q?: string; sort?: string; page?: string }>;
};

export default async function OrdersPage({ searchParams }: Props) {
  const { status, q, sort = 'date-desc', page = '1' } = await searchParams;
  const { rows, pages, current } = await getOrders({ status, q, sort, page: Number(page) });

  const href = (changes: Record<string, string>) => {
    const next = new URLSearchParams({ ...(status && { status }), ...(q && { q }), sort, ...changes });
    return '/dashboard/orders?' + next.toString();
  };

  return (
    <>
      <h1>Orders</h1>
      <nav aria-label="Status filter">
        <Link href={href({ status: '', page: '1' })}>All</Link>
        <Link href={href({ status: 'paid', page: '1' })}>Paid</Link>
        <Link href={href({ status: 'pending', page: '1' })}>Pending</Link>
      </nav>

      <table>
        <thead>
          <tr>
            <th>Order</th>
            <th>Customer</th>
            <th><Link href={href({ sort: sort === 'amount-desc' ? 'amount-asc' : 'amount-desc' })}>Amount</Link></th>
          </tr>
        </thead>
        <tbody>
          {rows.map((order) => (
            <tr key={order.id}>
              <td>#{order.id}</td>
              <td>{order.customer}</td>
              <td>{(order.amount / 100).toFixed(2)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <p>Page {current} of {pages}</p>
    </>
  );
}

Three points about this page. searchParams is a promise in current Next.js, so you await it. Reading it makes the route dynamic, rendered per request, which is correct here because the output depends on the query (see Static vs Dynamic Rendering). And the filter logic belongs in getOrders, a data function that should do the filtering in the database (WHERE, ORDER BY, LIMIT), never by loading every row and filtering in JavaScript.

Search params are user input. A visitor can type ?page=abc or ?sort=;drop into the address bar. Parse and whitelist every value before it reaches a query: allow only known sort keys, clamp the page to a valid range, and treat the search text as plain data, never as part of a query string (see Validating Input).

A live search box is a small Client Component that updates the URL while typing, usually with a short debounce, using useRouter or usePathname and useSearchParams from next/navigation. When the URL changes, the server component above re-runs and the table updates.

Here is the same design as a stand-in. The "URL" is the hash, the links build the next URL from the current one, and a function plays the part of getOrders. Click a filter, sort by amount, search for a name and page through the results, and watch the address line.

A dashboard table driven by URL state

Look at what is not in this component: there is no useState for the filter, the sort or the page. Every control is a link, and the table is a pure function of the URL. That is exactly what the Server Component version does, and it is why the pattern is so robust. Try typing a bad value into the address, for example #/orders?page=99 or #/orders?sort=nonsense: the whitelist and the page clamp keep the table valid.

Streaming panels with Suspense

The overview page shows a revenue panel, a recent-orders panel and a traffic panel. They come from different queries with different speeds. Without Suspense the page waits for the slowest one before it shows anything. With Suspense, each panel is wrapped in its own boundary: the fast panel appears immediately, and the slow ones show a skeleton until their data is ready.

TSX
// app/dashboard/page.tsx
import { Suspense } from 'react';
import { Revenue, RecentOrders, Traffic } from '@/components/stat-cards';
import { RevenueSkeleton, TableSkeleton, TrafficSkeleton } from '@/components/skeletons';

export default function Overview() {
  return (
    <>
      <h1>Overview</h1>
      <div className="grid gap-4 md:grid-cols-3">
        <Suspense fallback={<RevenueSkeleton />}>
          <Revenue />
        </Suspense>
        <Suspense fallback={<TableSkeleton />}>
          <RecentOrders />
        </Suspense>
        <Suspense fallback={<TrafficSkeleton />}>
          <Traffic />
        </Suspense>
      </div>
    </>
  );
}
TSX
// components/stat-cards.tsx
import { getRevenue } from '@/lib/data';

export async function Revenue() {
  const revenue = await getRevenue(); // an async Server Component
  return (
    <section className="rounded border p-4">
      <h2>Revenue</h2>
      <p className="text-2xl">{revenue.total}</p>
    </section>
  );
}

Each of Revenue, RecentOrders and Traffic is an async Server Component that fetches its own data. Because they are siblings, their requests start at the same time rather than one after another (see Fetching Data in Server Components). Next.js sends the page shell and the skeletons right away over a streamed response, then sends each panel's HTML when it is ready, and React swaps it in place. Visitors see a useful page in milliseconds.

Two more files finish the picture. A loading.tsx next to a page is a shortcut: Next.js wraps that page in a Suspense boundary using the file as the fallback. Use it for page-level loading, and use explicit <Suspense> for panel-level loading. And a good skeleton matches the final layout (same height, same width), so the page does not jump when content arrives. Layout shift is something Google measures (see Bundle Size and Core Web Vitals).

TSX
// components/skeletons.tsx
export function RevenueSkeleton() {
  return (
    <section className="rounded border p-4" aria-busy="true">
      <div className="h-5 w-24 animate-pulse rounded bg-gray-200" />
      <div className="mt-3 h-8 w-32 animate-pulse rounded bg-gray-200" />
    </section>
  );
}

The stand-in below uses real React 19 Suspense and the use hook. Each panel suspends on a promise with its own simulated delay (0.5, 1.5 and 2.5 seconds). Press Reload and watch the skeletons return and the panels arrive one by one, never blocking each other.

Panels that stream in behind skeletons

The whole page finishes after about 2.5 seconds, the time of the slowest panel, but the visitor sees real content after half a second. That is the difference between a loading spinner that blocks the page and streaming. Because the header and the layout are outside every boundary, they are visible from the first frame, as they are in a real dashboard.

Errors, empty states and access

A dashboard also needs the unhappy paths:

  • error.tsx next to a page catches an error thrown while rendering that segment and shows a fallback with a retry button, while the sidebar keeps working. It must be a Client Component.
  • Empty states. "No orders match" (as in the stand-in) is better than an empty table.
  • Access control. Never assume the /dashboard URL is hidden. Check the user's session and role in the layout and in every data function and Server Action, not only in the proxy file (see Authorization and Data Security).
  • Freshness. A dashboard usually wants live data. Leave panels uncached, or give them a short revalidate, and add a refresh control (see Revalidating Data).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it a good idea to keep table filters, sorting and page in the URL?

    URL state survives refreshes and can be shared. The server reads searchParams and renders the matching rows. Search params are still user input, so they must be validated.
  2. 2. What happens to the sidebar in dashboard/layout.tsx when you navigate from /dashboard to /dashboard/orders?

    Layouts are preserved across navigations between their child routes, so they keep state and do not re-render.
  3. 3. You wrap three async panels in three separate Suspense boundaries. What is the visitor's experience?

    Independent Suspense boundaries stream independently. Sibling components also start their fetches at the same time, so they do not form a waterfall.
  4. 4. Why should a skeleton match the layout of the final content?

    A skeleton of the same size prevents the page from jumping, which is better for users and for the Cumulative Layout Shift metric.
  5. 5. Where should the filtering of a large orders table happen?

    Loading every row to filter in JavaScript is slow and wasteful. Push filtering, sorting and paging into the query.

Summary

  • Use a nested layout.tsx for the dashboard frame. It persists across navigations between its pages.
  • Keep table state in searchParams: filters, search text, sort and page. The page is a Server Component, a pure function of the URL.
  • Treat search params as untrusted input: whitelist sort keys and statuses, clamp page numbers, and do the filtering in the database.
  • Wrap independent panels in their own <Suspense> boundaries, with skeletons that match the final layout, so fast panels never wait for slow ones.
  • Use loading.tsx for page-level loading and error.tsx for per-segment failures.
  • Enforce authorization in layouts, data functions and actions, not only in the proxy.

Next: Project: A Todo App with Server Actions