#Error: Dynamic server usage: Route /api/protected/roles couldn't be rendered statically because it u

1 messages · Page 1 of 1 (latest)

hybrid stumpBOT
#

Hi @lusty oxide. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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:

  1. Use the dynamic route 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.

  1. 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.

  2. For all routes under /api:
    If you want all routes under /api to 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.

Remember that making routes dynamic means they won't be cached and will be computed on each request, which might impact performance but is necessary for routes that need access to request-specific data.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: