DEV Community

Cover image for Shopify's Hydrogen vs. Next.js - Headless Battle
iskurbanov
iskurbanov

Posted on • Updated on

Shopify's Hydrogen vs. Next.js - Headless Battle

Article written by Philip Beauford for buildnextshop.com

Checkout the current best Hydrogen examples here:
hydrogentemplates.io

How the Shopify Hydrogen Framework compares to Next.js for Headless Architecture

Shopify has recently released its own opinionated React framework, named Hydrogen. As Shopify states, Hydrogen was built as a solution for developing custom headless Shopify storefronts. The first time I experimented with a Hydrogen demo project, I immediately noticed it felt very similar to Next.js.

The architecture and overall implementation is very similar to Next but there are a few key subtle differences in the approach from both. Next even has their own commerce solution with live demo that already support Shopify out of the box.

So then why was Next.js not enough? Why did Shopify feel the need to create their own Hydrogen framework?

Let's take a quick look at both frameworks for a few comparisons:

Hydrogen vs Next.js
When looking at the architecture, Hydrogen is using Vite which uses goLang, whereas Next uses SWC compiler which is built with Rust. So it's interesting to see the difference in choice of high performance languages.

Image description

Hydrogen comes with multiple custom Shopify Components, Hooks & Utilities which is obviously better for a more streamlined Shopify development experience. Whereas Next.js currently has no available Shopify Components requiring more custom work to be done.

Hydrogen also ships out of the box with Tailwind CSS and although Next.js can easily integrate tailwind, it is not included in the starter Next.js project.

A few similarities are both Hydrogen and Next use a page based routing system out of the pages directory and both Streaming SSR & React Server Components are available on each framework. However, Shopify claims to be more committed to Streaming SSR and Server Components overall, with Hydrogen being built around server components from the ground up.

Benefits of Hydrogen

In these articles Shopify Principal Engineer Ilya Grigorik mentions 5 general areas that separate Hydrogen from the rest:

  1. Streaming server-side rendering for fast non-blocking first render powered by Reacts Suspense Components.

  2. React Server Components for efficient, post-render component-level state updates.

  3. Built-in server and client data fetching primitives with smart cache defaults.

  4. Flexible page and sub-request cache policies to power dynamic and edge delivery.

  5. Oxygen Hosting.

All of these are great but not all are technically 100% exclusive to Shopify.

Options 3 and 4 are essentially general descriptions of custom solutions to optimize data use over the network with some improvement in user experience. As for Streaming SSR and React Server Components, they rely on React 18 features that have no official release, but are not exclusively provided by Hydrogen. Other frameworks will (and do) have the same or similar features available.

For example, Next.js, with its large developer base, supports both of these React 18 features, although currently in Alpha.

If all of that is true, why is Hydrogen still a likely better solution for Headless Shopify development?

Hydrogen appears to have a slight advantage when it comes to Streaming SSR & React Server Components, as mentioned by Ilya Grigorik:

“One advantage that we have at Shopify, even compared to let’s say Next.js, is that we’re starting anew. We don’t have an existing ecosystem of apps that we need to move over to this new world of React Server Components.” “We’re big fans of what they’re building,” he said regarding Vercel and Next.js, “and in many ways the architecture is similar. But they are approaching it from another direction."

Vercel is about:

  • Build it
  • Push it to the edge
  • Then add layers of dynamic capabilities.

"We think that given the needs of commerce, we actually need to start with the inverse. Which is, assume everything is dynamic by default, and then expose the right APIs and capabilities to be static.”

Grigorik continued,,

“This is not a debate about dynamic vs. static. You need both.” “Some, or perhaps even substantial parts of some storefronts” can be “cached and served from the edge” (the traditional JAMstack model).

But Shopify customers that choose Hydrogen will be building their storefronts fresh, using JavaScript. Shopify was “willing to make some more opinionated and forward-looking bets about technology choices,” said Grigorik. So it chose to build around React Server Components and create a “dynamic by default” framework.

“We saw a gap,” Grigorik summarized, “when we surveyed the existing tools, where it’s really hard — not impossible, but really hard — to get server-side rendering and dynamic commerce working well together.”

So it seems although both frameworks are perfectly suitable for ECommerce, Hydrogen is definitely the most aligned with the Shopify ecosystem, as I would expect, but also most aligned with any merchant looking for a Dynamic first approach.

The real key to the Shopify edge in all of this will be Oxygen, Shopify's hosted V8 worker runtime enabling server-side requests to the Storefront API with localhost speed.
Image description

Integrating Hydrogen into Next.js

For those who ask, why can't I just use both? There is a hybrid approach being discussed, which utilizes both by integrating custom Hydrogen components into a Next.js project.

To integrate Hydrogen components in your Next.js project, first we need to install some packages:

npm install @shopify/hydrogen next-transpile-modules --legacy-peer-deps --save
Enter fullscreen mode Exit fullscreen mode

Next we need to instruct Next.js to compile @shopify/hydrogen from ESM (ES Modules) to CJS (CommonJS) by editing next.config.js with this block:

const withTM = require("next-transpile-modules")(["@shopify/hydrogen"]);
module.exports = withTM({
  reactStrictMode: true,
});
Enter fullscreen mode Exit fullscreen mode

Shopify will be supporting multiple export types in a future version of Hydrogen so this is a temporary step for now.

To fetch Shopify storefront data in your Next.js project, Shopify recommends calling the Storefront API on the server similar to this code (example only):

// pages/products/[handle].jsimport {Product} from '@shopify/hydrogen';


export async function getStaticProps({params}) {
  const {data} = getShopifyData({query: QUERY, variables: {handle: params.handle}});

  return {
    props: data,
    revalidate: 5,
  };}


export function Product({data}) {
  return (
    <Product product={data.product}>
      {/** ... */}
    </Product>
  );}
Enter fullscreen mode Exit fullscreen mode

There are a few current limitations when using Hydrogen inside of Next.js. You are not able to use the useShopQuery custom hook as it is meant to be run in Hydrogens Server Components.

Josh Larson of Shopify recommends writing a utility file like getShopifyData({ query, variables }), which takes your storefront API credentials and makes a GraphQL query that you can then use in Next.js functions.

Here is just one example of a potential getShopifyDatautility:

const storeDomain = "hydrogen-preview.myshopify.com"
const storefrontToken = "3b580e70970c4528da70c98e097c2fa0"


export async function getShopifyData(query, variables) {
  return await fetch(`https://${storeDomain}/api/2021-10/graphql.json`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      "X-Shopify-Storefront-Access-Token": storefrontToken
    },
    body: JSON.stringify({
      query,
      variables
    })
  }).then((response) => {
    return response.json()
  })
}
Enter fullscreen mode Exit fullscreen mode

It will be interesting to see how Oxygen impacts the growth of Shopify's new Hydrogen framework. Although if Hydrogen does prove to be the best 'dynamic first' React framework for Ecommerce, some good early growth could be expected.

For an example of how to use Shopify with Next.js and Tailwind CSS check out this sample starter project: https://github.com/iskurbanov/shopify-next.js-tailwind

Checkout the example website and full tutorial at BuildNextShop.com where we create a fully production ready Shopify Headless store using Next.js!

Top comments (4)

Collapse
 
ryanleichty profile image
Ryan Leichty

Have you tried building a project with Next.js using Hydrogen components?

Collapse
 
iskurbanov profile image
iskurbanov

Not yet!

Collapse
 
mveckovic profile image
Mike M. Veckovic

what about next.js aside from shopify?

Collapse
 
iskurbanov profile image
iskurbanov

What do you mean?