In Next.js, Server-Side Rendering (SSR) is primarily implemented through the getServerSideProps function of page-level components. This function executes on every page request, enabling you to fetch data on the server and pass it as props to your page.
Triggering Server-Side Rendering programmatically typically involves initiating a request from the client to a specific page route on the server, which then invokes the getServerSideProps function to complete the rendering process.
Here is a simple example to illustrate this:
Suppose you have a Next.js page /pages/products.js that displays a product list. To obtain the server-rendered product list, implement the getServerSideProps function:
js// pages/products.js export async function getServerSideProps(context) { // Fetch data from an API const res = await fetch('https://api.example.com/products'); const products = await res.json(); // Pass the fetched data as props to the page return { props: { products } }; } function Products({ products }) { return ( <div> <h1>Products</h1> {products.map((product) => ( <div key={product.id}> <h2>{product.name}</h2> <p>{product.description}</p> </div> ))} </div> ); } export default Products;
To trigger server-side rendering for this page from client-side code—for example, after a user enters a search term in a search bar—you can use Router or window.location to navigate to the page with query parameters:
js// Function handling search events const handleSearch = (searchTerm) => { // Navigate to the page with query parameters Router.push({ pathname: '/products', query: { search: searchTerm }, }); };
In this example, calling handleSearch causes the client to send a request to the server, which executes getServerSideProps based on the provided query parameters and re-renders the /products page.
Note that getServerSideProps receives the context parameter, containing detailed request information such as query parameters and request headers. This allows you to customize server-side logic based on the passed query parameters.
If you need to trigger an API endpoint, execute logic within it, and return necessary data for rendering, create an API route to handle server-side logic, then call this API from the client using fetch.