#Error: Dynamic server usage: Route /api/protected/roles couldn't be rendered statically because it u
1 messages · Page 1 of 1 (latest)
Next.js is trying to render your API route statically because, by default, it attempts to optimize routes by statically generating them when possible. However, for API routes that need to be dynamic (like those that use cookies, headers, or other request-specific data), you need to explicitly tell Next.js to render them dynamically.
Why Next.js Tries to Render API Routes Statically
In newer versions of Next.js, particularly in the App Router, GET functions in Route Handlers are no longer cached by default, but you might still encounter this issue depending on your setup and Next.js version Route Handlers.
How to Make API Routes Dynamic
You can make your API routes dynamic in several ways:
- Use the
dynamicroute segment config option:
export const dynamic = 'force-dynamic';
export async function GET(request) {
// Your API logic here
}
This tells Next.js to always render this route dynamically at request time Dynamic Rendering.
-
Use dynamic APIs or uncached data fetches:
If your route uses cookies, headers, or other dynamic APIs, Next.js should automatically switch to dynamic rendering. However, you might need to be explicit about it Server Rendering Strategies. -
For all routes under
/api:
If you want all routes under/apito be dynamic, you can create a catch-all segment config file:
// app/api/[...path]/route.js
export const dynamic = 'force-dynamic';
export async function GET(request) {
// Handle the request
}
Or you could add the dynamic config to each individual API route file.
If you're using the Pages Router (not App Router), you might need to use a different approach, as the configuration options differ between the two routing systems.