Next.js offers several methods to define dynamic routes in your application.
One way to signal a dynamic route is by directly accessing request objects within your route handler. For instance, you can fetch request headers or cookies from next/headers
. Another option would be useSearchParams
from next/navigation
:
import { cookies, headers } from 'next/headers';
import { useSearchParams } from 'next/navigation';
export default function Home() {
headers();
cookies();
useSearchParams();
These actions implicitly suggest to Next.js that the route relies on dynamic data.
Using the dynamic
Export
For explicit control, Next.js allows you to export a dynamic
constant within your route handler. This constant accepts different options to fine-tune the dynamic behavior.
Setting dynamic
to 'force-dynamic'
ensures that Next.js treats the route as dynamic, even if it doesn't detect any dynamic data access:
export const dynamic = 'force-dynamic';
Other options for the dynamic
constant include:
'auto'
: The default setting, allowing Next.js to determine dynamic behavior automatically based on code analysis.'error'
: The route is considered dynamic if there's an error during data fetching.'force-static'
: Forces the route to be static, even if dynamic data access is detected.
Revalidation for Static Content
While dynamic routes offer flexibility, there are times when we desire the performance benefits of static generation but with occasional content updates. Next.js supports this with a feature we'll look at in the next lesson.