Skip to article content
LESSON 11 / 28

Server data fetching and the DAL

Build a data boundary that validates inputs, enforces permissions, returns minimal views and keeps independent reads independent.

What you will be able to do

  • Separate transport, domain data and browser-facing DTOs.
  • Read data directly from server components without unnecessary internal HTTP hops.
  • Explain request memoization, persistent caching and authorization as separate concerns.

Read where the required credentials belong

An async Server Component can call server data code directly. If the database or upstream credential is private, that is a natural place to keep the dependency. A Route Handler is useful when an HTTP caller needs an endpoint, but the server page does not automatically need to call its own endpoint over HTTP. An internal round trip adds transport overhead and another failure surface without creating a meaningful security boundary by itself.

Keep data code outside the visual component when several callers need the same rules. A Data Access Layer is a place to centralize validated queries, permission checks and safe returned shapes. It is not merely a folder named dal. The design succeeds when a page, action and endpoint cannot accidentally use three different ownership rules for the same record.

Validate both incoming values and outgoing views

URL parameters, form values and request headers are untrusted inputs. Validate their shape, then use a safe database query interface. Upstream JSON is also untrusted at runtime even when TypeScript annotates it. Check required fields before consuming it and distinguish invalid upstream data from a legitimate empty result. Type assertions do not transform or validate network data.

After access is allowed, return a DTO with only the fields the browser needs. For a public product, title and displayed price may be allowed while supplier costs and internal credentials are not. A private account view also requires object-level permission checks. Do not pass the complete record to a client component and rely on the JSX to hide sensitive fields.

Server execution

app/lib/public-product.ts
import 'server-only';
const records = [
  { id: 'keyboard', title: 'Mechanical keyboard', priceCents: 6500, supplierCostCents: 3100 }
];
export async function getPublicProduct(id: string) {
  if (!/^[a-z0-9-]+$/.test(id)) return null;
  const product = records.find(record => record.id === id);
  if (!product) return null;
  return { id: product.id, title: product.title, priceCents: product.priceCents };
}

PAUSE AND PREDICT

An async Server Component and a Route Handler both need the same product lookup. Which structure usually avoids unnecessary work without duplicating rules?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Deduplication is not permission or durability

Two components can need the same data in one render. Request-scoped memoization can avoid repeated work during that rendering scope. Persistent caching reuses results across later requests and therefore needs a separate identity, lifetime and invalidation policy. React cache used for render-pass deduplication should not be described as a universal cross-request cache, and its wrapper is not a replacement for endpoint authorization.

A viewer’s identity can be deduplicated within the appropriate request work, but permission to access a resource still matters wherever that resource is read or changed. A shared cache key must represent all relevant inputs if it stores a reusable view. For sensitive personalized output, decide whether caching is appropriate at all before adding it. The next lessons make these decisions explicit rather than hiding them behind a helper name.

Represent failures and avoid accidental waterfalls

Missing records, denied access and unavailable infrastructure have different meanings. Return a controlled absence result when the record is legitimately missing; use the application’s authorization response for denied access; let unexpected infrastructure failures reach an appropriate error boundary with server-side diagnostics. Do not turn every exception into an empty list, because that makes a broken service look like valid no-results data.

If catalogue categories and featured products are independent, start them before awaiting their combined result. If an order query needs the verified viewer ID, that dependency must remain sequential. Parallelism is a property of the dependency graph, not a blanket instruction to put every call in Promise.all. The pure exercise below tests a permission and projection policy. The real lab connects the same reasoning to actual server execution and responses.

PAUSE AND PREDICT

An upstream response is annotated as Product[] using a TypeScript assertion, but it contains missing prices. What did the assertion establish?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEReact render-pass memoization is a universal persistent cache.
A more accurate model

Name its scope. Deduplication during rendering is different from reuse across requests and does not replace permission checks.

How to check it

N09, N10 and N11 distinguish data and cache scopes; the DAL section keeps authorization separate.

CLAIM TO CHALLENGEReturning [] for every exception is good resilience.
A more accurate model

It conflates infrastructure failure with legitimate empty data. Preserve meaningful error categories so the UI and diagnostics can respond correctly.

How to check it

N27 covers error handling; the server-data-fetching lesson separates missing, denied and unavailable results.

Mistakes to catch in your own code

  • Calling your own Route Handler from a Server Component is not automatically necessary or safer.
  • A TypeScript annotation does not validate JSON received from a network.
  • Request memoization does not replace authorization or define a persistent cache policy.

Write it by hand

JavaScript logic playground

Authorize and project a private document

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Implement solve({viewer,document}). Either value may be null. A document has id, tenantId, ownerId, title and internalNotes; a viewer has id, tenantId and role.
  2. Return {status:401,data:null} without a viewer, then 404 if the document is absent. A tenant mismatch or non-owner who is not an admin returns 403.
  3. For an allowed read, return status 200 and only {id,title}. role=admin grants access only inside the same tenant. This is a policy kernel, not a real session verifier.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 5 test cases
  1. Anonymous request

    Input

    {
      "viewer": null,
      "document": null
    }

    Expected

    {
      "status": 401,
      "data": null
    }
  2. Owner receives minimal view

    Input

    {
      "viewer": {
        "id": "u1",
        "tenantId": "t1",
        "role": "member"
      },
      "document": {
        "id": "d",
        "tenantId": "t1",
        "ownerId": "u1",
        "title": "Draft",
        "internalNotes": "private"
      }
    }

    Expected

    {
      "status": 200,
      "data": {
        "id": "d",
        "title": "Draft"
      }
    }
  3. Admin cannot cross tenants

    Input

    {
      "viewer": {
        "id": "u2",
        "tenantId": "t2",
        "role": "admin"
      },
      "document": {
        "id": "d",
        "tenantId": "t1",
        "ownerId": "u1",
        "title": "Draft",
        "internalNotes": "private"
      }
    }

    Expected

    {
      "status": 403,
      "data": null
    }
  4. Same-tenant nonowner denied

    Input

    {
      "viewer": {
        "id": "u2",
        "tenantId": "t1",
        "role": "member"
      },
      "document": {
        "id": "d",
        "tenantId": "t1",
        "ownerId": "u1",
        "title": "Draft",
        "internalNotes": "private"
      }
    }

    Expected

    {
      "status": 403,
      "data": null
    }
  5. Missing record

    Input

    {
      "viewer": {
        "id": "u1",
        "tenantId": "t1",
        "role": "member"
      },
      "document": null
    }

    Expected

    {
      "status": 404,
      "data": null
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const { viewer, document } = input;
  if (!viewer) return { status: 401, data: null };
  if (!document) return { status: 404, data: null };
  if (viewer.tenantId !== document.tenantId) return { status: 403, data: null };
  if (viewer.id !== document.ownerId && viewer.role !== 'admin') return { status: 403, data: null };
  return { status: 200, data: { id: document.id, title: document.title } };
}

Tenant isolation is checked before role elevation, so admin does not accidentally become a global cross-tenant permission.

The response deliberately omits internalNotes. In production, viewer must come from verified server session data, never a trusted client object.

Verify it in a real Next.js application

Next.js application lab

Trace public and protected server reads

Open the local application route /dashboard after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Inspect getCatalog, currentUser, the dashboard Workspace component and /api/tasks/[id]. Trace input, session verification, tenant filtering and returned fields separately.
  2. Compare a public /api/catalog request with an anonymous /api/tasks/north-1 request. Then sign in as Ada and request both north-1 and south-1 directly.
  3. Switch to Grace and repeat the South request. Inspect /api/session and the /session props to confirm that public identity fields are returned without cookie tokens or signing-key material.
  4. As an extension, extract the repeated protected task lookup into a server-only DAL function used by both page and handler. Preserve entry-point-appropriate redirects or status responses and add a cross-tenant regression case.

Check the behavior

  • The task endpoint rejects an anonymous request and does not expose a different tenant's task to the current identity.
  • A valid same-tenant request returns the documented task DTO.
  • Browser-visible session data excludes tokens and signing secrets.
  • If the DAL extraction is implemented, it preserves both page and API behavior rather than replacing an authorization check with a UI assumption.
Review the application reasoning

The identity selector is a training fixture. The actual read and write boundaries still verify the resulting session; a browser-hidden button is not permission evidence.

Signed session claims can remain stale until their expiry. The lab demonstrates that tradeoff explicitly, while a production permission policy may require current authoritative data.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01Should a Server Component fetch its own API route?

    Usually it can call the underlying server data function directly when both are in the same application. The endpoint remains useful for external or browser HTTP callers. I share the validated domain logic rather than force the server page through an unnecessary HTTP hop, while keeping authorization at each callable entry and data boundary.

    Follow-up questions

    • When is an external service boundary justified?
    • How do you avoid duplicating validation?
  2. 02Does response.json() return trusted typed data?

    No. The response is runtime data and can violate the expected contract. I check status and validate the relevant payload shape before using it. A type assertion can silence the compiler but cannot prevent missing fields or wrong types. Invalid payloads need an explicit failure path rather than silently rendering corrupt data.

    Follow-up questions

    • How do you distinguish empty from invalid?
    • Where should validation errors be logged?
  3. 03How does request memoization differ from persistent caching?

    Memoization within a rendering scope deduplicates repeated work for that scope. Persistent caching intentionally reuses results later and requires a key, lifetime and invalidation rules. Neither mechanism establishes permission to read a record. I describe the scope before claiming that a function is cached.

    Follow-up questions

    • What happens in a Route Handler outside a React render pass?
    • How should tenant identity affect a cache key?
  4. 04What makes a data-access layer useful?

    It centralizes real boundary behavior: validated identifiers, safe queries, authorization and minimal returned DTOs. A directory full of raw database calls with inconsistent checks does not provide that benefit. I verify that pages, actions and endpoints use the same domain rules and test unauthorized and cross-tenant access explicitly.

    Follow-up questions

    • Should the client choose its own tenant ID?
    • Which fields can leave the server?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

A same-tenant admin can read other users’ documents, but must never read another tenant’s documents. Which check order preserves this policy?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.