Skip to main content

Next.js App Router: Why Your Route Handlers Are Returning Stale Data

 You have migrated an API endpoint to the Next.js App Router. It works perfectly in development (next dev). However, once you build and deploy to production, the endpoint behaves strangely. You update a record in your database, hit the endpoint to fetch the updated list, and receive the old data. No matter how many times you refresh, the data remains stale until you rebuild the application.

This is not a bug in your database logic. It is a fundamental misunderstanding of how the App Router handles caching compared to the Pages Router.

The Root Cause: Static by Default

In the older Pages Router (pages/api), every API route was treated as a Dynamic Serverless Function. It executed on every request.

In the App Router (app/api), Next.js inverts this paradigm. Route Handlers are Static by Default.

When you run next build, Next.js analyzes your Route Handlers. It will automatically cache the response of a GET handler at build time and serve that static JSON indefinitely if:

  1. The handler is a GET method.
  2. The handler does not use the Request object.
  3. The handler does not use dynamic functions like cookies() or headers().
  4. You have not explicitly defined a segment configuration.

If your code looks like the snippet below, Next.js executes the database query once during the build process, saves the result as a static file, and serves that file to every user.

// app/api/users/route.ts
import { NextResponse } from 'next/server';
import { db } from '@/lib/db'; // hypothetical ORM

// ❌ PROBLEM: Next.js treats this as a static asset at build time.
export async function GET() {
  const users = await db.user.findMany();
  return NextResponse.json(users);
}

The Fix: Opting Out of Static Caching

There are three ways to fix this, depending on your caching requirements.

Solution 1: Force Dynamic (Recommended for APIs)

If your endpoint represents real-time data (e.g., user profiles, inventory stock, database records), you need to explicitly tell Next.js to opt out of static generation.

Add the dynamic segment configuration variable to your route file.

// app/api/users/route.ts
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

// ✅ FIX: Forces the route to be executed on every request
export const dynamic = 'force-dynamic';

export async function GET() {
  const users = await db.user.findMany();
  return NextResponse.json(users);
}

Solution 2: Incremental Static Regeneration (ISR)

If you want the performance benefits of caching but need the data to update periodically (e.g., a "Trending Posts" endpoint that updates every minute), use the revalidate segment configuration.

// app/api/trending/route.ts
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

// ✅ FIX: Caches the response, but invalidates it every 60 seconds
export const revalidate = 60;

export async function GET() {
  const posts = await db.post.findMany({
    where: { trending: true }
  });
  
  return NextResponse.json(posts);
}

Solution 3: Using the Request Object (Implicit)

Next.js will switch to dynamic mode if you access the Request object. While this works, it relies on implicit behavior. It is cleaner to use Solution 1 (force-dynamic) to make your intent explicit in the code, but you should recognize this pattern:

// app/api/search/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

// ✅ FIX: Accessing 'request' signals to Next.js that this depends on incoming data
export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const query = searchParams.get('q');

  const results = await db.item.findMany({
    where: { name: { contains: query ?? '' } }
  });

  return NextResponse.json(results);
}

Why This Works

The export const dynamic = 'force-dynamic' line modifies the build output. When the Next.js compiler encounters this constant, it skips the static generation phase for this specific route segment.

Instead of generating a static .json file, Next.js compiles this route into a Serverless Function (or executes it on the existing Node.js server instance). When a request hits the endpoint:

  1. Static (Default): The server returns the pre-computed hash/file created at build time. Latency is near-zero, but data is frozen.
  2. Dynamic (force-dynamic): The server connects to your database, runs the query, and generates the response on the fly.
  3. ISR (revalidate): The server serves the cached file until the revalidate window expires. The next request triggers a background regeneration of the data.

Conclusion

The shift from Pages Router to App Router requires a mental model shift from "everything is dynamic" to "everything is static until proven otherwise."

If your App Router GET handlers are returning stale data, you are likely falling into the default static optimization bucket. Explicitly export dynamic = 'force-dynamic' or configure revalidate to ensure your API reflects the current state of your database.

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...