Dynamic Functions in Next.js
Using functions like `cookies()` or `headers()` forces a Next.js page to be rendered dynamically for each request. This is key for personalized content or pages depending on search params.
WHY IT EXISTS: Next.js aims to be as static as possible for performance. However, many web pages need to be dynamic, showing content based on the specific user or request. Dynamic functions provide an explicit way to tell Next.js when a page must be rendered on-demand.
THE MENTAL MODEL: Think of dynamic functions as "static-breakers." By default, Next.js wants to pre-render everything at build time. The moment you use a function like cookies() or headers() inside a component, you are telling Next.js, "Stop! The output of this component depends on information I can only get when a user makes a request. You must render this on the server for every visit."
HOW IT WORKS: When Next.js analyzes your page components, it detects the usage of these specific functions. If one is found, it marks the route as dynamic. Instead of generating a static HTML file at build time, it prepares the route to be rendered by a server function at request time. This allows your code to access request-specific information like cookies, headers, and URL parameters before sending the final HTML to the user.
WHEN TO USE IT: Use dynamic functions when a page's content is not universal and must be tailored for each request. Three common scenarios are: first, personalization based on user login status (read from a cookie); second, A/B testing based on a cookie or header; third, displaying data based on URL search parameters (e.g., ?query=...).
WHEN NOT TO USE IT: Avoid using dynamic functions on pages that are the same for every user, like marketing pages, blog posts, or documentation. Using one accidentally will make the page slower and more expensive to serve because it will be server-rendered for every user instead of being served instantly from a CDN cache.
ONE CANONICAL EXAMPLE: A common use case is displaying a user's name in a dashboard. You would use the cookies() function to read the session cookie, verify the user, and fetch their data. Because cookies() is a dynamic function, Next.js knows this page must be rendered at request time to access the unique cookie for each visitor.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.