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:
- The handler is a
GETmethod. - The handler does not use the
Requestobject. - The handler does not use dynamic functions like
cookies()orheaders(). - 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:
- Static (Default): The server returns the pre-computed hash/file created at build time. Latency is near-zero, but data is frozen.
- Dynamic (
force-dynamic): The server connects to your database, runs the query, and generates the response on the fly. - ISR (
revalidate): The server serves the cached file until therevalidatewindow 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.