Cache Side-Effects (get-ssg-metadata.js)
Examine compile-time side effect trackers, dynamic cookie injections, and static routing redirect scripts.
Key File Location: ./dinou/core/get-ssg-metadata.js💡 Overview
In a standard server rendering setup, setting cookies or executing redirects is handled via HTTP headers (Set-Cookie or Location: /url). However, once a page is pre-compiled and served statically from disk cache, the server does not run any dynamic code, making HTTP header manipulation impossible.
Dinou solves this using Compile-Time Side-Effect Injection. If a Server Component sets a cookie or triggers a redirect during static compilation, the compiler captures it, serializes it with get-ssg-metadata.js, and prepends it to the static HTML file as an inline <script> block that runs immediately on the browser.
📊 Metadata Processing Flow
The chart below traces the translation of compile-time side effects into executable inline scripts:
⚡ Client-Side Side-Effects Injection
This technique enables features like localized routing redirects and session cookie setup for static pages:
- Cookie Setup: Generates immediate
document.cookieassignments. If the compiler recorded a cookie clearance, it setsMax-Age=0to delete it in the browser. - Immediate Redirects: Generates a
window.location.hrefredirect script. Because it sits at the top of the HTML header, it executes before styles or page elements load, preventing layout flicker. - IIFE Encapsulation: Wraps scripts in an Immediately Invoked Function Expression (IIFE) to avoid polluting the global window namespace.
⚙️ Complete Code Walkthrough
Below is the full, complete code of get-ssg-metadata.js:
function processMetadata(effects) {
if (!effects) return "";
let scriptContent = "";
// 1. Process cookie operations (setting or clearing)
if (effects.cookies && effects.cookies.length > 0) {
effects.cookies.forEach((ck) => {
const name = JSON.stringify(ck.name);
const value = JSON.stringify(ck.value || "");
const path = JSON.stringify(ck.options?.path || "/");
if (ck.isClear) {
// Clear cookie by setting expiration to 0
scriptContent += `document.cookie = ${name} + "=; Max-Age=0; path=" + ${path} + ";";`;
} else {
scriptContent += `document.cookie = ${name} + "=" + ${value} + "; path=" + ${path} + ";";`;
}
});
}
// 2. Process redirect actions
if (effects.redirect) {
scriptContent += `window.location.href = "${effects.redirect}";`;
}
if (!scriptContent) return "";
// 3. Return an inline script tag to execute immediately upon browser parse
return `<script>(function(){ ${scriptContent} })();</script>`;
}
module.exports = {
processMetadata,
};