Swizec Teller - a geek with a hatswizec.com

    A fun security bug with static rendering – CodeWithSwiz #31

    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

    Paywall when internet is good

    And here's what it looks like if your internet is slow ...

    Paywall when internet is bad

    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 πŸ₯³

    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

    Did you enjoy this article?

    Published on June 1st, 2021 in CodeWithSwiz, Technical, Livecoding, Gatsby

    Learned something new?
    Want to become an expert?

    Here's how it works πŸ‘‡

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters πŸ’Œ 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. πŸ‘Œ"

    ~ Ashish Kumar

    Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer?Β I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own? Β Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first πŸ’° on the side with ServerlessReact.Dev

    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 ❀️

    Created bySwizecwith ❀️