Next.js caching on Google Cloud ☁️

Glenn Bostoen
2 min readJun 16, 2022

We use Google Cloud run to deploy our Next.js websites on. To have this play nicely with the preview mode that is built into Next.js, you need to configure some things properly.

For preview mode to work, we first need to define 2 API endpoints:

  • One endpoint enable the preview mode: /api/preview
  • Another optional route to disable preview mode: /api/exit-preview

So to activate the preview mode, we check if the query parameters contain a secret and if it matches the one we’ve configured in our environment variables. This allows us to secure preview mode only for authorized users. Additionally, we have a slug query parameter which allows us to redirect to a certain page on our website.

# File /pages/api/preview.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { getFirst } from 'util/string';export default function preview(req: NextApiRequest, res: NextApiResponse) {
// Check the secret
// This secret should only be known to this API route and the CMS
if (req.query.secret !== process.env.PREVIEW_SECRET) {
return res.status(401).json({ message: 'Invalid token' });
}
// Enable Preview Mode by setting the cookies
res.setPreviewData({});
// Redirect to the path from the parameters
res.redirect(getFirst(req.query.slug) ?? '/');
res.end();
}

For the deactivation of preview mode, we just remove the preview context and redirect to any page if passed in the query parameters.

# File /pages/api/exit-preview.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { getFirst } from 'util/string';export default function handler(req: NextApiRequest, res: NextApiResponse) {
// Clears the preview mode cookies.
// This function accepts no arguments.
res.clearPreviewData();
if (req.query.slug) {
// Redirect to the path from the fetched post
res.redirect(getFirst(req.query.slug));
} else {
res.end('Preview mode disabled');
}
}

This works well on Cloud Run directly but if we combine this with a Load Balancer and CDN with the default cache settings, we see that we are unable to hit the preview mode of the website. This is caused by the fact that the load balancer can’t make a distinction between this preview/ live mode because it doesn’t have any knowledge of it.

We can solve this by making use of the cookies that are set by Next.js. It uses:

  • __next_preview_data
  • __prerender_bypass

There is an option on the Load Balancer to make use of these cookies, see including named cookies. It was made GA in January. Unfortunately, these settings were not yet available via Terraform, which we use as a best practice to set up our infrastructure on Google Cloud. We made a Pull Request last week, and it made it into the new release v4.25.0 so now it’s possible to manage this from Terraform as well 🎉.

--

--