Summer '23 Editions: Fast, flexible, future-proof—How we’re evolving Hydrogen
July 27, 2023
It’s been just over a year since Hydrogen 1.0 shipped — and what a year. There are now thousands of merchants building with the Hydrogen and Oxygen stack, and hundreds already running in production today, processing over $1 billion in sales. We’re thrilled with the enthusiasm and feedback from the growing number of merchants, developers, and agencies that have built this community with us.
Our vision for Hydrogen is to let you spend less time building boilerplate code, and more time building your brand. By building components and utilities that are just opinionated enough, we want to help you skip the boring parts of spinning up a new headless commerce site, so you can concentrate on expressing what’s unique about your business.
We’ve made a lot of progress in pursuit of that vision in the last few months, and there’s more to come soon. We’d like to extend a special thank you to Matt Seccafien, Daniel Rios Pavia, Dave Yen, and all those in the Hydrogen community that made these releases possible. Let’s take a look at where we are today, and where we’re going next.
Recently shipped
Start faster with the CLI
Starting a new Hydrogen project with the Shopify CLI now gives you more options. Since the framework is built to work with Shopify’s APIs, we can do things like scaffold out standard app routes, add your favorite styling library, and configure language and currency settings. We’ve made it so that you can have everything you need from homepage to checkout in less than 2 minutes.
We’ve also added support for mock.shop, which allows you to test-drive the Storefront API without needing an API token, or a Shopify account. That means you can start building right away, based on realistic product data.
And if you already have a Shopify store, you can now connect your live product inventory to your Hydrogen app with a single command: npx shopify hydrogen link. Once your store is linked to your local development environment, your app automatically starts displaying your actual product inventory.
Finally, if you want to save yourself some keystrokes and don’t want to prefix every Hydrogen command with npx shopify hydrogen, you can now shorten it to simply h2 with one command: npx shopify hydrogen shortcut.
A shortcut to better shopping carts
Managing a shopping cart is one of the absolute fundamentals of digital commerce, and one of the hardest to get right. You have to manage state for products, variants, quantities, discounts, user authentication and more, and display it all in a fast, reactive UI.
So we thought long and hard about how to rebuild the Hydrogen cart. We wanted it to be fast and performant, with sensible defaults that require minimal configuration, while still empowering developers to customize it for their most complex use cases.
Our first and biggest bet was on making the cart server-side first, built on old-school form actions. Maintaining state on the server, via Shopify’s Storefront API, is positive in a few ways. It means that adding to or editing the cart doesn’t require JavaScript, slashing time-to-interactive to zero. In other words: if you can see an “Add To Cart” button on the product page, you can click it. The server-first approach also allows us to send less total JavaScript down the wire, speeding up page loads across the board.
But that doesn’t mean we have to give up on a more interactive cart. Thanks to Remix’s support for optimistic UI updates, we can still provide a smooth, expressive shopping experience on the client side.
The new Hydrogen cart features pre-built abstractions for all the most common cart operations: adding, editing, or deleting product variants, metafields, and other attributes; and applying and validating discount codes. Hydrogen is all about giving you shortcuts, not lock-ins — so you can easily define your own custom methods on the cart, giving you the flexibility you’d expect from a headless commerce architecture.
Here’s the implementation of a basic Add To Cart button:
app/routes/cart.tsx
import { CartForm } from "@shopify/hydrogen";
// The action only executes on the server
export async function action({ request, context }) {
// The cart is setup on the context,
// so available in any of your actions and loaders
const { session, cart } = context;
// Here we assume all requests are to add lines, but you might want to switch on
// the action value to determine whether to add, remove, or update line items.
const { action, inputs } = CartForm.getFormInput(await request.formData());
// Built-in and custom cart methods are both available on the cart object
const { cart: cartResult, errors } = await cart.addLines(inputs.lines);
// Update the cookie headers because a new cart might have been created
const headers = cart.setCartId(cartResult.id);
return json(
{
cart: cartResult,
errors,
analytics: {
cartId,
},
},
{ headers },
);
}
function AddToCartButton({ lines }) {
return (
A better variant selector
Many product pages require the ability to select from available variants — think a T-shirt that comes in different sizes, or lipstick in different shades. In Hydrogen, we recommend that selecting a variant should update the URL. There are two reasons for this: it means that search engines can index individual product variants, and that each selected variant has a unique link that can be bookmarked or shared on social media.
Hydrogen now includes a <VariantSelector /> form component that makes it easier to build selectors that behave consistently, load faster, and render server-side for better performance and progressive enhancement.
Here’s an example of how you could use the new <VariantSelector /> component on a product page:
app/components/ProductForm.tsx
import { VariantSelector } from "@shopify/hydrogen";
const ProductForm = ({ product }) => {
return (
<>
<VariantSelector
handle={product.handle}
options={product.options}
>
{({ option }) => (
<>
<div>{option.name}</div>
<div>
{option.values.map(({ value, isAvailable, to, isActive }) => (
<Link>
to={to}
prefetch="intent"
className={isActive ? "active" : isAvailable ? "" : "opacity-80"}
>
{value}
</Link>
))}
</div>
</>
)}
</VariantSelector>
// Add to Cart button could go here
</>
);
};
A new approach to pagination
Handling pagination is a chore that has to be done in any app, and no one likes doing chores! So we’ve released a new ready-made Pagination component that you can drop into index pages.
The Storefront API uses cursor pagination, where individual pages are denoted by a hash, not an integer. We’ve opted to use that hash as a URL parameter to manage pagination state. This might not make for the most beautiful URLs— but in our testing, the benefits far outweigh the cost. Using URLs for state management is transparent and less error-prone. Updating the URL on scroll or load events is trivial, and it’s easier to correctly restore scroll position when traversing browser history. Pages can be rendered and cached on the server, making them faster for customers and search crawlers. Overall, the performance wins overwhelmed any minor aesthetic quibbles about URLs.
Here’s how you’d paginate a product collection in routes/collections/$handle.tsx with the new Pagination component:
/routes/collections/$handle.tsx
import { getPaginationVariables, Pagination } from "@shopify/hydrogen";
import { useLoaderData, Link } from "@remix-run/react";
import { json } from "@shopify/remix-oxygen";
export async function loader({ params, context, request }) {
const variables = getPaginationVariables(request, {
pageBy: 8,
});
const { products } = await context.storefront.query(COLLECTION_QUERY, {
variables: {
handle: params.handle,
...variables,
},
});
return json({
products,
});
}
export default function () {
const { products } = useLoaderData();
return (
<Pagination connection={products}>
{({ nodes, NextLink }) => (
<>
{nodes.map((product) => (
<Link key={product.id} to={product.id}>
{product.title}
</Link>
))}
<NextLink>Load next products</NextLink>
</>
)}
</Pagination>
);
}
Of course, you can configure this component for different behaviors, depending on what you need. For example, here’s an implementation where products automatically load as you scroll down the collections page.
A re-imagined <Image /> component
Earlier this spring we released a major refactor of Hydrogen’s built-in Image /> component. This update further streamlined its API and added smarter defaults, since we can tailor our component design to match how Shopify handles media. There’s now just a single required data prop, which seamlessly accepts theImageobject returned by the Storefront API. It renders a fully responsive image tag, with multiple srcset values served on demand by Shopify’s image CDN, along with width, height, and aspect-ratio values that reduce cumulative layout shift.
The new <Image /> component is fully backward-compatible and gives you a variety of ways to customize its behavior — including fixed-size images and even custom loaders to integrate third-party image CDNs.
Custom types with GraphQL codegen
One of the reasons we love GraphQL at Shopify is because you get type safety built right into the API. This feature also powers autocomplete in most common IDEs, making it faster and easier to query and call the right fields. But with pre-generated types, it’s an all-or-nothing deal: your code editor imports and suggests autocompletes for every type — regardless of the API data you’re actually using in your app.
Codegen makes typing and autocompletion smarter, by evaluating your data queries in real time, and then generating the appropriate types on the fly. This means your IDE can give you genuinely helpful code hints that are tailored to your Hydrogen app. Try GraphQL Codegen in your local dev environment today with npm run dev --codegen-unstable.
Next-level logging for Oxygen
Oxygen is Hydrogen’s not-so-secret weapon — a globally distributed serverless hosting runtime built specifically to serve Hydrogen apps at blazing speed and planetary scale. For free.
Oxygen has now added support for log drains, which allow developers to pipe Oxygen events to third-party logging management platforms, including DataDog, New Relic, or Splunk. This new feature enables long-term archiving, detailed introspection, and performance auditing for those merchants with the most demanding monitoring needs. Log drains are available today for merchants on the Shopify Plus plan.
Tomorrow’s Remix, today
When the new version of Hydrogen came out in February, its foundational framework, Remix, was at version 1.12. Since then, Remix has had a number of exciting releases — notably adding support for hot module reloading and built-in support for top CSS frameworks.
Even better, we’ve been able to adopt many of Remix’s future features too. This is all thanks to Remix’s “future flags”, where future breaking changes are released as opt-in features today. It’s why we can already support Remix’s enhanced<ErrorBoundary /> components, more granular handling for HTML meta tags, and a flatter file structure for nested routes.
Remix 2 is coming, and while we don’t have an exact date, thanks to future flags, we don’t need one! When you adopt Hydrogen, you get the power of Remix under the hood, the flexibility to adopt exciting new features as soon as they ship, plus a clear path to predictable upgrades on your schedule, not ours.
A new Customer Account API
Launching today in developer preview is the new Customer Account API . It allows you to build secure, authenticated, and personalized experiences that give your customers a passwordless single sign-on across all Shopify surfaces — from Liquid to Hydrogen and non-Hydrogen custom storefronts, all the way through to checkout. On top of being more convenient for customers, a standalone API for this sensitive data gives you enhanced security, with separate API permission scopes, independently managed OAuth2 tokens, and safer, more granular access for third-party apps.
We’re confident this new API is going to unlock powerful new capabilities for Hydrogen, and for headless commerce more broadly. In the future, we plan to give developers access to more Shopify primitives — things like B2B, returns, subscriptions, and card vaulting. See our example of how you can implement the Customer Account API in Hydrogen, try it out today, and be sure to share your feedback on Discord as we head towards general availability.
What’s next
There’s lots more to come over the next few months. We’ll bring you more ready-made components that can reduce the time you spend on boilerplate code; we also have big ambitions for improving the local development experience and giving you more tools to help you keep your Hydrogen apps fast and performant.
Better sorting, filtering, and search
One near-term priority we have for Hydrogen is improved support for large product catalogs. Drop-in pagination support is one example of this. Better sorting, filtering, and predictive search is up next. And just like pagination, these capabilities are already part of the Storefront API, but we can provide better off-the-shelf components that make these features far easier to implement.
Like our other recent releases, we’ll focus on performant components that work server-side first, with progressive enhancements in the client and minimal built-in styling.
Deeper dives with dev tools
Another area where we think we can make it faster, easier, and more productive to build with Hydrogen is with our developer tooling.
By default, Hydrogen builds a single worker file, deployed to a serverless runtime. That makes it fast — but we’ve heard from the community that it also makes it tough to debug and optimize Hydrogen sites.
So we’ll be bringing you better tools to analyze your app before you deploy to production. That means things like analyzing your worker bundle, request and subrequest timing, CPU and memory profiling, and improved sourcemap support.
Help grow the roadmap
We have plenty of ideas for how to continue Hydrogen’s evolution, but what we really want is to hear from you. Join us on Discord, star Hydrogen on GitHub, or follow @ShopifyDevs on Twitter for all the updates as we ship them, and to share your feedback.
The last year has been transformative for headless commerce at Shopify, in many different ways. Thousands of merchants are now building on top of the Hydrogen and Oxygen stack, deploying ambitious new shopping experiences every single week. We’re excited to see these tools continue their growth — but we’re even more excited to see what you build with them next.
Get building
Spin up a new Hydrogen app in minutes.
See documentation