Skip to content

Page Caching

Stuart George edited this page Dec 3, 2024 · 2 revisions

The pageHandler function in the router.go file is responsible for rendering pages efficiently by leveraging a caching mechanism. This document provides an overview of how the cache works and instructions for bypassing it.

How the Cache Works

1. Cache Initialization:

The cache is initialized with a default expiration time of 5 minutes (pageCacheDuration) and a cleanup interval of 10 minutes:

var (
    pageCacheDuration = time.Minute * 5
    pageCache         = NewCache[string, templ.Component](pageCacheDuration, 10*time.Minute)
)

2. Cache Retrieval:

When a page request is received, the function first checks if the page’s HTML is already cached:

cacheKey := path

if html, found := pageCache.Get(cacheKey); found {
    c.Response().Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", pageCacheDuration/time.Second))
    return cc.RenderComponent(http.StatusOK, html)
}

If a cached version is found, it is returned immediately to avoid redundant computations.

3. Cache Miss:

If the page is not found in the cache, it is generated dynamically by:

  • Fetching necessary data from the database (e.g., settings, page details, ancestors, and children).
  • Rendering the page using the fetched data.
  • Storing the rendered page’s HTML in the cache for future use:
pageCache.Set(cacheKey, html, pageCacheDuration)

4. No-Cache Pages:

Pages marked with NoCache in the database bypass the cache and are served with HTTP headers to prevent caching:

if page.Page.NoCache {
    c.Response().Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
    c.Response().Header().Set("Pragma", "no-cache")
    c.Response().Header().Set("Expires", "0")
}

How to Bypass the Cache

You can bypass the cache and force a fresh rendering of the page by sending a Cache-Control: no-cache header in the request. When this header is detected, the cached entry for the page is deleted:

if strings.Contains(c.Request().Header.Get("Cache-Control"), "no-cache") {
    pageCache.Delete(cacheKey)
}

Example of a Cache-Bypass Request

Use the following curl command to bypass the cache for a specific page:

curl -H "Cache-Control: no-cache" http://example.com/some-page

Alternatively use chrome dev tools to disable caching. This ensures that the page is re-fetched and re-rendered without using the cached version.

Clone this wiki locally