Skip to content

docs: Current cacheing docs are invalid for NextJS App Router  #5625

Open

Description

@jeff-computers

Area of Improvement

Currently documented tRPC cacheing methods (https://trpc.io/docs/server/caching) won't work with Next.JS' app router as they rely on setting headers which Next.js now overrides (https://nextjs.org/docs/app/api-reference/next-config-js/headers#cache-control).

As such - there is no documentation or examples (anywhere, as far as I can tell) for how to manage cacheing of tRPC endpoints running in a NextJS App Router environment.

Link to related docs

https://trpc.io/docs/server/caching

Update 30/7/24

I was just revisiting this issue and the existing strategy of declaring cache-control headers for API routes within next.config.js works for TRPC endpoints.

// next.config.js
...
  headers: async () => {
    return [
      {
        source: "/api/trpc/yourRouteName",
        headers: [
          {
            key: "Cache-Control",
            value: "public, s-maxage=15, max-age=15",
          },
        ],
      },
    ];
  },

Activity

  1. added
    📚 documentation / examples
    on Apr 12, 2024
  2. DawnMD commented on Sep 19, 2024

    @DawnMD

    @jeffrey-computers tRPC does batch request, so suppose if I want cache for a single router from multiple routers then I don't think that headers workaround will work! Correct me if I'm wrong!

  3. dionne-chelini commented on Jul 7, 2025

    @dionne-chelini
    Image

    Here is a summary how I Enabled CDN Caching for Specific tRPC Procedures in Next.js

    Problem

    • tRPC batches all requests by default, making individual endpoint caching impossible
    • All tRPC calls use POST requests, which many CDNs don't cache
    • Need selective caching for specific procedures while maintaining batching for others

    Solution Overview

    Used splitLink to conditionally separate cacheable requests from batched requests,
    then set appropriate Cache-Control headers in the API route handler.

    Key Changes Made

    1. Client-Side: Configure splitLink

    // ApiClientProvider.tsx

      splitLink({
        condition(op) {
          return Boolean(op.context.skipBatch)
        },
        true: httpLink({...}),      // Non-batched GET requests
        false: httpBatchLink({...}) // Batched POST requests
      })
    

    (Full Example Down below)

    1. API Route: Handle Both GET and POST Requests

    // app/api/[trpc]/route.ts

      const cacheablePaths = ["lesson.fetchLesson", "lesson.byId",
      "lesson.getAllLessons"]
    
      async function wrappedHandler(req: NextRequest) {
        // Check GET requests in URL
        if (method === "GET" && isCacheable(url)) {
          shouldCache = true
        }
        // Check POST requests in body
        else if (method === "POST") {
          const body = await req.text()
          shouldCache = cacheablePaths.some(path => body.includes(path))
          // Reconstruct request since body was consumed
        }
    
        if (shouldCache) {
          response.headers.set("Cache-Control", "public, s-maxage=864000, 
      stale-while-revalidate=60")
        }
      }
    
    1. Frontend: Use skipBatch Context

    // Component making the call

      apiClient.lesson.fetchLesson.useQuery(
        { lessonNumber, languageCode, unitId },
        {
          trpc: {
            context: { skipBatch: true }
          }
        }
      )
    

    Result

    • GET requests with proper cache headers: cache-control: public, s-maxage=864000,
      stale-while-revalidate=60
    • Selective caching for specific procedures only
    • Other requests remain batched for performance
    • CDN now caches lesson data for 10 days

    FYI

    If you are running your dev environment and looking for Vercel Headers, ex. x-vercel-cache, you won't see any of these in development, only in production will vercel add these headers.

    Key Insight

    The tricky part was handling both GET and POST requests in the route handler, since
    some configurations still use POST even with skipBatch: true, and reading the
    request body consumes it (requiring reconstruction).

    Full Examples

    "use client"
    
    import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
    import { httpBatchLink, httpLink, splitLink } from "@trpc/client"
    import customTransformer from "api/trpc/customTransformer"
    import type { PropsWithChildren } from "react"
    import { useState } from "react"
    import { apiClient } from "../lib/api-client"
    
    export function ApiClientProvider({ children }: PropsWithChildren) {
      const baseUrl = typeof window !== "undefined" ? window.location.origin : ""
    
      const [queryClient] = useState(() => new QueryClient())
      const [trpcClient] = useState(() =>
        apiClient.createClient({
          links: [
            splitLink({
              condition(op) {
                console.log("op", op)
                // check for context property `skipBatch`
                return Boolean(op.context.skipBatch)
              },
              true: httpLink({
                url: baseUrl + "/api",
                transformer: customTransformer,
              }),
              false: httpBatchLink({
                url: baseUrl + "/api",
                transformer: customTransformer,
              }),
            }),
          ],
        })
      )
      return (
        <apiClient.Provider client={trpcClient} queryClient={queryClient}>
          <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
        </apiClient.Provider>
      )
    }
    
    
  4. trpc-bot commented on Nov 3, 2026

    @trpc-bot
    Collaborator

    🤖 The caching docs now have a Next.js App Router section: set Cache-Control in responseMeta on fetchRequestHandler in your route handler, and send cacheable public queries through httpLink with a splitLink so they aren't batched with private ones.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    📚 documentation / examples

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions