Configure server caching on Next.js

Most Next.js apps on App Hosting can keep the normal Next.js defaults. However, if your instances encounter Memory limit exceeded errors, you may need to set experimental.isrFlushToDisk: false to keep the cache in memory and prevent instances from restarting.

By default, Next.js caches the pages and data it renders at runtime, such as pages generated with Incremental Static Regeneration (ISR), route handler responses, and fetch results. It keeps them in memory and also writes them to files in your app's .next directory. Next.js doesn't remove these files.

On App Hosting, your app runs on Cloud Run, where the file system is in memory. Files written to it count toward the memory allocated for each serving instance (memoryMiB) until the instance shuts down. If your app renders many distinct pages at runtime, for example dynamic routes with parameters that aren't generated at build time, instances can exceed their memory limit and restart. Cloud Run then logs an error like Memory limit of 512 MiB exceeded with 515 MiB used. See the Cloud Run documentation on file system access for details.

Keep the cache in memory

To stop Next.js from writing its cache to the file system, set experimental.isrFlushToDisk to false in your next.config.js file:

// @ts-check

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    isrFlushToDisk: false,
  },
};

module.exports = nextConfig;

Next.js then keeps cached content only in memory, up to cacheMaxMemorySize (default 50 MB), and removes the least recently used entries when the cache is full. Each serving instance has its own cache, which is lost when the instance restarts.

Create a commit that includes these changes and push it to your live branch. Then, wait for the App Hosting rollout to complete.