Sample: Caching based on authentication
Overview
This example demonstrates how to configure caching based on authentication.
PREREQUISITES: You must set up a Sitefinity renderer application and connect it to your Sitefinity CMS application. For more information, see Install Sitefinity in Next.js mode.
Building the component
- We modify the
middleware.ts
file to check whether the request is made by an authenticated or anonymous user based on the request's cookies.
const hasAuthCookie = request.cookies.getAll().some(cookie => cookie.name.includes('AspNet.Cookies'));
-
If the request is not authenticated, we rewrite it to go through a custom cached slug where the cache type and revalidation time are configured. We also set an additional header, x-cached-route-processed, to indicate that the request has already been processed.
-
Then, include this middlewareCache
function into the app's middleware file. First, we check to ignore all requests that have already been processed by verifying the presence of the x-cached-route-processed
header.
if (request.headers.has('x-cached-route-processed')) {
return NextResponse.next();
}
-
Then, add the new step from middlewareCache
.
const resultCache = await middlewareCache(request);
if (resultCache instanceof Response) {
return resultCache;
}
-
Create an additional slug, such as /cached with a page.tsx
, to process the rewritten request. Configure the cache type and revalidation time for this slug according to your specific requirements. The revalidate duration is necessary if you want cache invalidation to occur beyond just when the app is rebuilt. This slug will handle the rewritten request.
export const dynamic = 'force-static';
export const revalidate = 30
Full middleware sample
You can access the full middleware sample at the Sitefinity Next.js samples GitHub repository.
Run the sample
This sample is available in Sitefinity’s GitHub repository. You can run and play with it.
To do this, perform the following:
- Go to Sitefinity’s GitHub repository Sitefinity NextJS samples.
- Expand Code and click Download ZIP.
- Extract the files on your computer.
- In the extracted folder, navigate to
\nextjs-samples-main\nextjs-samples-main\src \auth-cache
folder.
- In the command console run npm install.
- Open the
.env.development
file.
- In section
PROXY SETTINGS
, change the SF_CMS_URL
property to the URL of your Sitefinity CMS site.
If you have deployed Sitefinity CMS on the IIS, point to “https://localhost:<https_port>".
- In the command console run npm run dev.