How Dynamic Content Works on a Static Site
How "Dynamic" Content Works on a Static Site
A common misconception in web development is that you need a running server (Node.js, Python, PHP) to have dynamic content like blog posts or user-specific views. In this article, I'll deconstruct how I built the blog system for this portfolio using a Static-First approach.
The Architectural Shift
In a traditional Dynamic Setup, the server is the brain:
- User requests
/blog/post-1. - Server queries a SQL Database.
- Server renders HTML using a template engine.
- User receives the final HTML.
In a Static-Dynamic Setup, the browser is the brain:
- User visits
/post?id=post-1. - Server simply serves a generic
post.htmlfile. - JavaScript in the browser wakes up and looks at the URL.
- JavaScript fetches the raw data (Markdown/JSON) and renders it on the fly.
Step 1: Client-Side Routing
We use the URL's "search parameters" to pass information without reloading the page logic.
// Capturing the intent from the URL
const params = new URLSearchParams(window.location.search);
const slug = params.get('id'); // e.g., "static-site-logic"
Step 2: The "JSON Database"
Instead of a heavy database, we maintain a lightweight posts.json. This acts as a map for our application, telling us where each file lives.
{
"id": "static-site-logic",
"title": "Making Static Sites Smart",
"file": "blog/posts/content.md"
}
Step 3: Asynchronous Markdown Rendering
We use the Fetch API to download the Markdown file and a library like marked.js to transform it into clean HTML.
async function loadContent(filePath) {
const raw = await fetch(filePath);
const text = await raw.text();
document.getElementById('content').innerHTML = marked.parse(text);
}
Why This Wins for Portfolios
- Zero Loading Time: Files are served from a CDN edge.
- Security: There's no server-side code to exploit. No SQL injection, no server crashes.
- Maintenance: To add a new post, I simply drop a Markdown file into a folder and update a JSON list. No database migrations required.
- Developer Experience: I can write my blog posts in VS Code, just like I write my code.
Summary
By offloading the rendering logic to the client's browser, we gain all the benefits of a modern CMS without the overhead and complexity. This portfolio is a testament to the power of simpler, distributed architectures.