Next.js and Server-side Rendering

One of the great things about Next.js is that it allows you to render your content in different ways depending on your website or web application's use case. These include pre-rendering with Static Generation, Server-side Rendering, or even updating content at runtime with Incremental Static Regeneration.

By default, our Next.js Starter pre-renders content using Static Generation, while updating content on the fly at runtime with Incremental Static Regeneration. However, you can opt-out of this and pre-render your pages on each request using data returned by an exported getServerSideProps function.

Updating the Rendering Method

As mentioned earlier, by default, our Next.js Starter pre-renders content using Static Generation. To use Server-side Rendering, update the following code:

[...slug].js

Replace the code in the [...slug].js file to the following:

import Layout from "components/common/Layout";
import { getModule } from "components/agility-pageModules";
import SiteHeader from "components/common/SiteHeader";
import { getAgilityPageProps  } from "@agility/nextjs/node";

export async function getServerSideProps({ params, req, res, query, preview, resolvedUrl, locale, locales, defaultLocale }) {

	try {

		if (!preview) {
			//CACHE THIS PAGE FOR 60s
			res.setHeader('cache-control', 'public, max-age=60')
		}

		//place all global here
		const globalComponents = {
			header: SiteHeader,
		};

		const agilityProps = await getAgilityPageProps({
			preview,
			params,
			locale,
			getModule,
			defaultLocale,
			globalComponents,
		});

		if (!agilityProps) {
			// We throw to make sure this fails at build time as this is never expected to happen
			throw new Error(`Page not found`);
		}


		return {
			// return all props
			props: agilityProps
		};
	} catch (error) {
		return {
			props: {
				error: `An error occurred: ${error}`
			}
		}
	}
}

const AgilityPage = (props) => {
	if (props.error) {
		return JSON.stringify(props)
	} else {
		return <Layout {...props} />;
	}
};

export default AgilityPage;

index.js

Replace the code in the index.js file to the following:

//this is just a pointer to the catch-all route and logic for all CMS driven pages (i.e. even rootpage is dynamic from the CMS)
export { default, getServerSideProps } from './[...slug]';

With these changes in place, your Next.js website or web application will now pre-render pages on each request.

For more information on getServerSideProps, see the Next.js documentation here.