Blog

  • Safe JSON in script tags: How not to break a site

    <script> tags follow unintuitive parsing rules that can break a webpage in surprising ways. Fortunately, it’s relatively straightforward to escape JSON for script tags.

    Just do this

    • Replace < with \u003C in JSON strings.
    • In PHP, use json_encode($data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES) for safe JSON in <script> tags.
    • In WordPress, use wp_json_encode with the same flags.

    You don’t have to take my word for it, the HTML standard recommends this type of escaping:

    The easiest and safest … is to always escape an ASCII case-insensitive match for “<!--” as “\x3C!--“, “<script” as “\x3Cscript“, and “</script” as “\x3C/script“…

    This post will dive deep into the exotic script tag parsing rules in order to understand how they work and why this is the appropriate way to escape JSON.

    (more…)
  • These types are not the same

    When working with TypeScript types, the design of our types is important. One choice we often see is to define an interface, but many times a union is preferable to a single interface. Here are two types that can be used in similar ways, below I’ll explain why the union is often preferable:

     
    TypeScript
    interface SessionDataMega {
    isLoggedIn: boolean;
    user?: { name: string };
    }
    type SessionDataUnion =
    | { isLoggedIn: false; user?: never; }
    | { isLoggedIn: true; user: { name: string }; };

    SessionDataMega is a wider type. It’s flexible enough to cover all the different shapes of data we expect — and some we don’t!

    SessionDataUnion is a union of two narrower types. The union consists of two types (members of the union) that are both more specific than the interface.

    (more…)
  • Volta vs. nvm for JavaScript tooling

    I work on several JavaScript projects that use nvm (Node Version Manager) for managing Node.js versions. I’ve recently started using Volta to replace nvm and have been very impressed.

    I’ll explain the differences between Volta and nvm, and why I’m excited about Volta. Volta’s benefits stem from these two enhancements:

    • Volta installs and uses project-defined tools automatically.
    • Volta has better handling of global scripts.
    (more…)