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.tsfile 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'));
2. 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.
```TypeScript
if (!hasAuthCookie && !request.nextUrl.pathname.startsWith('/render-lazy')) {
const headers = request.headers;
headers.set('x-cached-route-processed', 'true');
let url = new URL(request.url);
url.pathname = '/cached' + request.nextUrl.pathname;
return NextResponse.rewrite(url, {
request: {
headers: headers
}
});
}
```
- Then, include this
middlewareCachefunction into the app's middleware file. First, we check to ignore all requests that have already been processed by verifying the presence of thex-cached-route-processedheader.
if (request.headers.has('x-cached-route-processed')) { return NextResponse.next(); }
4. Then, add the new step from middlewareCache.
const resultCache = await middlewareCache(request); if (resultCache instanceof Response) { return resultCache; }
5. 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-cachefolder. - In the command console run
npm install. - Open the
.env.developmentfile. - In section
PROXY SETTINGS, change theSF_CMS_URLproperty 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.