Skip to content

A proposal for Next.js cache invalidation on demand by setting a custom server

Notifications You must be signed in to change notification settings

FSaldanha/nextjs-cache-purging

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Update

In February 2022, Next.js released a built-in On-demand Incremental Static Regeneration in beta stage. This new solution likely makes this project obsolete.

Next.js Cache Purging

Introduction

When you use getStaticProps in a page, Next.js does Automatic Static Optimization by prerendering it to static HTML.

This occurs for static or static generated pages which have routers predefined with getStaticPaths (at build time), incremental static generated pages with fallback configuration (at first request) or incremental static regenerated pages with a revalidate parameter defined (in the background, after first request when page is stale).

In the prerendering process, Next.js emits HTML and JSON files and saves it by default in .next/server/pages directory. Besides, content is cached using a slighty modified version of LRU Cache.

Until this moment (February 2021), Next.js does not have a native feature for invalidating cache on demand, which could be used with an API for triggering content update without having to rebuild the application, although maintainers had already demonstrated interest in implementing it (see here and here).

Possible solution

By setting a custom server (see server.js in this repo), it's possible to ask Next.js to delete prerendering files and purging LRU Cache for a specific URL, by justing appending the parameter purge=1 to it. This appears to preserve Automatic Static Optimization, even though documentation states the opposite.

Caveats

  • Experimental code! Do not use it in production.
  • It cannot be deployed to Vercel.

About

A proposal for Next.js cache invalidation on demand by setting a custom server

Resources

Stars

Watchers

Forks