Dynamic Rendering in Next.js: What It Is and How It Works
Next.js, dynamic rendering means generating web pages on the server at request time instead of ahead of time. This allows pages to show fresh data or personalized content by running code each time a user visits, using features like getServerSideProps.How It Works
Dynamic rendering in Next.js works like a restaurant kitchen that prepares meals only when customers order them, instead of cooking everything in advance. When a user visits a page, the server runs the page's code to fetch fresh data and build the HTML on the spot. This means the page always shows the latest information.
Next.js uses a special function called getServerSideProps that runs on the server for every request. It fetches data or performs logic, then sends the fully rendered page to the browser. This approach is great when content changes often or depends on the user.
Example
This example shows a Next.js page that fetches the current time on the server every time you load it, demonstrating dynamic rendering.
import React from 'react'; export async function getServerSideProps() { const currentTime = new Date().toISOString(); return { props: { currentTime } }; } export default function TimePage({ currentTime }) { return ( <main> <h1>Current Server Time</h1> <p>The time on the server is: {currentTime}</p> </main> ); }
When to Use
Use dynamic rendering when your page needs to show up-to-date or user-specific data that changes often. For example:
- Dashboards showing live stats
- User profiles with personalized info
- Content that updates frequently, like news or stock prices
This method ensures users always see fresh content but can be slower than pre-built pages because the server does work on each request.
Key Points
- Dynamic rendering generates pages on the server for every request.
getServerSidePropsis the main Next.js function for this.- It is best for frequently changing or personalized content.
- It can be slower than static rendering but ensures fresh data.