Hey Swiz, you know everyone can download your book for free right? ~ a helpful twitter DM
I knew, but I didn't think anyone else would find it 😅
CodeWithSwiz is a weekly live show. Like a podcast with video and fun hacking. Focused on experiments and open source. Join live most Tuesday mornings
Here's what /downloads looks like, if you haven't bought Serverless Handbook
And here's what it looks like if your internet is slow ...
Awkward.
The paywall waits for JavaScript to load, the page to render, then springs into action to look for a <div id="lock"></div>
element and hide everything below. A clever React effect makes that happen:
useLayoutEffect(() => {
if (typeof window !== "undefined") {
window.requestAnimationFrame(() => {
if (unlocked) {
hidePaywall(paywallDiv);
} else {
showPaywall(paywallDiv);
}
});
}
}, [unlocked]);
If running in the browser and page locked, show paywall.
What's the matter, bub?
The Serverless Handbook, like all my sites, uses Gatsby to work faster. Statically rendered when you deploy.
You get to build your whole site in React with all its benefits, serve as fast static HTML, then re-hydrate into a typical React app. Works great when you're not being fancy.
I was being fancy.
The paywall waits until React runs to hide content. That way search engines can see the full content and humans can't.
Unless they disable JavaScript, which normal humans don't. Yes I know, there's dozens of you, dozens!
But when internet is slow this becomes a problem. React takes so long to run that you can casually finish reading a whole chapter or download all the files before the paywall stops you.
How we fixed it
The solution is obvious in retrospect: Don't render locked content you doodoo!
First we found the paywall code that decides if a page is locked
// Paywall.js
const hasLock =
typeof window !== "undefined" && document.querySelector("#lock");
// 👇
const hasLock = LOCKED_PAGES.includes(pagePath);
Used to work in browser only and look for a special lock div. Static rendering was unlocked by default.
Now looks at a list of configured locked pages.
Second we changed how page content renders.
// layout.js
{
props.children;
}
<Paywall />;
// 👇
{
contentUnlocked ? (
<main id="content">{props.children}</main>
) : (
<main id="content" dangerouslySetInnerHTML={{ __html: html }} />
);
}
<Paywall />;
Page layout used to render its children and let the <Paywall>
handle hiding.
Now it renders the full page when it's unlocked and a custom-crafted chunk of HTML when it's locked.
Third we build the cut-off HTML.
// layout.js
let html;
if (!contentUnlocked) {
html = ReactDOMServer.renderToString(props.children).split(
'<div id="lock"></div>'
)[0];
}
ReactDOMServer
lets you take any React fragment and render to a string. Works on the server, at build time, or in the browser.
You can then manipulate that HTML.
In our case, props.children
holds the full React fragment for page content with no other fuss. Guaranteed by Gatsby.
That means we can hackily split by <div id="lock"></div>
, take the head, and render with dangerouslySetInnerHTML
. Now there's no flash of unlocked content 🥳
The styling is messy because we rendered those children outside a <ThemeProvider>
.
Then I deployed to production and it failed completely. No paywall. 🥲
Cheers,
~Swizec
Continue reading about A fun security bug with static rendering – CodeWithSwiz #31
Semantically similar articles hand-picked by GPT-4
- Hacking the React AST for fun and profit – #CodeWithSwiz ep34
- Sometimes your worst code is your best code
- Exploring NextJS with a headless CMS, pt4 – CodeWithSwiz
- Why serverless fits side-projects perfectly
- Build privacy-focused blazing fast tweet embeds – CodeWithSwiz 30
Learned something new?
Read more Software Engineering Lessons from Production
I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.
Subscribe below 👇
Software Engineering Lessons from Production
Join Swizec's Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️