Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    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

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

    Did you enjoy this article?

    Continue reading about A fun security bug with static rendering – CodeWithSwiz #31

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

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

    Created by Swizec with ❤️