I want my NextJS App Router API code to execute on every page request from a browser. That is, when using API Routes with the Page Router I have code like this that gets executed on every request (in production mode).
/pages/api/route1.ts
export async function GET(request: Request) {
return new Response(
"Hello, from /api/test1/routes.ts " + new
Date().toLocaleString()
);
}
app/api/route1.ts
export async function GET(request: Request) {
return new Response(
"Hello, from /api/test1/routes.ts " + new
Date().toLocaleString()
);
}
That is to say, the result is that when I run the first code, the date changes on every request (in production), yet when I run the second code, the date sticks to whatever it was at build time.
My questions is, if I want to use the app router, how can I get the same behavior as I had before in the pages Router?
However, when I do basically the same thing with RSC's (React Server Components) technology using the App Router, the component is run at build time and never run again. Here is that code:
What you are experiencing is that the response of the route handler is considered to be static and thus cached because you don't use any dynamic functions such as accessing cookies, headers or accessing path or search parameters.
To fix this and force the route handler to be dynamically invoked on each request without any caching add the following route segment config option to your route handler:
export const dynamic = 'force-dynamic'
More details on the dynamic
segment config options are described in the Next.js docs.