No articles found
Try different keywords or browse our categories
Fix: Dynamic server usage Next.js error
Quick fix for 'Dynamic server usage' error in Next.js. Learn how to handle dynamic data fetching and server components properly.
The ‘Dynamic server usage’ error occurs when Next.js detects dynamic data fetching that cannot be prerendered at build time. This happens when server components attempt to access dynamic data that varies per request, such as user-specific data or request headers, without proper configuration.
How the Error Happens
❌ Error Scenario - Dynamic Data Without Configuration:
// ❌ This will cause a dynamic server usage error
// app/page.js
export default async function HomePage() {
// ❌ Dynamic data that varies per request
const userAgent = request.headers.get('user-agent'); // ❌ 'request' is not defined
const currentTime = new Date().toISOString(); // ❌ Dynamic per request
const res = await fetch(`https://api.example.com/data?time=${currentTime}`);
const data = await res.json();
return <div>{data.content}</div>;
}
❌ Error with Dynamic Params in Fetch:
// ❌ This will cause an error
// app/user-profile/page.js
export default async function UserProfile() {
// ❌ Cannot access request-specific data in static generation
const token = cookies().get('auth_token');
const userId = token ? getUserIdFromToken(token.value) : null;
if (userId) {
const res = await fetch(`https://api.example.com/users/${userId}`);
const user = await res.json();
return <div>Welcome {user.name}</div>;
}
return <div>Please log in</div>;
}
✅ Quick Fix - Handle Dynamic Server Usage
Solution 1: Configure Dynamic Options
// ✅ Allow dynamic usage with configuration
// app/page.js
export const dynamic = 'force-dynamic'; // ✅ Always run dynamically
export default async function HomePage() {
// ✅ Now dynamic data is allowed
const currentTime = new Date().toISOString();
const res = await fetch(`https://api.example.com/data?time=${currentTime}`);
const data = await res.json();
return (
<div>
<h1>Dynamic Page</h1>
<p>Current time: {currentTime}</p>
<p>Data: {data.content}</p>
</div>
);
}
Solution 2: Selective Dynamic Options
// ✅ Configure specific dynamic behaviors
// app/dashboard/page.js
export const dynamic = 'force-dynamic'; // ✅ Force dynamic rendering
export const revalidate = 0; // ✅ Disable caching
export default async function DashboardPage() {
// ✅ Access request-specific data
const res = await fetch('https://api.example.com/user-dashboard', {
headers: {
'Cache-Control': 'no-cache',
},
});
const data = await res.json();
return (
<div>
<h1>Dashboard</h1>
<p>Last updated: {new Date().toLocaleTimeString()}</p>
<div>{JSON.stringify(data)}</div>
</div>
);
}
Solution 3: Dynamic Segments in App Router
// ✅ Handle dynamic segments properly
// app/products/[id]/page.js
export const dynamicParams = true; // ✅ Allow dynamic params
export default async function ProductPage({ params }) {
const { id } = params;
// ✅ Dynamic fetch based on params
const res = await fetch(`https://api.example.com/products/${id}`);
const product = await res.json();
return (
<div>
<h1>{product.name}</h1>
<p>Updated: {new Date(product.updatedAt).toLocaleString()}</p>
</div>
);
}
// ✅ Generate static paths for known routes
export async function generateStaticParams() {
// ✅ Pre-generate some static paths
const res = await fetch('https://api.example.com/products');
const products = await res.json();
return products.slice(0, 10).map((product) => ({
id: product.id.toString(),
}));
}
Solution 4: Using Dynamic with Revalidation
// ✅ Dynamic with controlled revalidation
// app/news/page.js
export const dynamic = 'force-dynamic';
export const revalidate = 30; // ✅ Revalidate every 30 seconds
export default async function NewsPage() {
const res = await fetch('https://api.example.com/latest-news');
const news = await res.json();
return (
<div>
<h1>Latest News</h1>
<p>Fetched at: {new Date().toLocaleTimeString()}</p>
<ul>
{news.items.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}
Solution 5: Client-Side Data for Dynamic Content
// ✅ Server Component with static content
// app/profile/page.js
export const dynamic = 'force-static'; // ✅ Try to make static
export default function ProfilePage() {
return (
<div>
<h1>Profile</h1>
{/* ✅ Dynamic content loaded client-side */}
<UserProfile />
</div>
);
}
// ✅ Client Component for dynamic data
// components/UserProfile.js
'use client';
import { useState, useEffect } from 'react';
export default function UserProfile() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// ✅ Client-side fetch with dynamic data
async function fetchUser() {
try {
const res = await fetch('/api/user');
const userData = await res.json();
setUser(userData);
} catch (error) {
console.error('Error fetching user:', error);
} finally {
setLoading(false);
}
}
fetchUser();
}, []);
if (loading) return <p>Loading profile...</p>;
if (!user) return <p>User not found</p>;
return (
<div>
<p>Welcome, {user.name}!</p>
<p>Last login: {user.lastLogin}</p>
</div>
);
}
Solution 6: Dynamic Server Actions
// ✅ Use server actions for dynamic operations
// app/actions.js
'use server';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
export async function getUserProfile() {
// ✅ Server action can access request context
const token = cookies().get('auth_token');
if (!token) {
redirect('/login');
}
const res = await fetch('https://api.example.com/profile', {
headers: {
'Authorization': `Bearer ${token.value}`
}
});
return res.json();
}
// ✅ Use server action in component
// app/protected/page.js
import { getUserProfile } from '../actions';
export default async function ProtectedPage() {
// ✅ Dynamic data fetching via server action
const user = await getUserProfile();
return (
<div>
<h1>Protected Content</h1>
<p>Hello, {user.name}!</p>
</div>
);
} Related Articles
Fix: cookies() can only be used in Server Components error Next.js
Quick fix for 'cookies() can only be used in Server Components' error in Next.js. Learn how to properly use cookies in Server Components.
Fix: fetch is not cached by default in Next.js error
Quick fix for 'fetch is not cached by default' error in Next.js. Learn how to properly cache fetch requests in Server Components.
Fix: Headers was called outside a request scope error Next.js
Quick fix for 'Headers was called outside a request scope' error in Next.js. Learn how to properly use headers in Server Components.