Custom Size – 1.

For developers getting started with Shopify Hydrogen: Our development guidelines are now public

Hi. I'm Representative and CTO Takasaki.
Our company is also developing frontends using the Shopify genuine headless commerce framework Hydrogen.
Because it is still a new framework, there are few information and we often work hard to develop, but I think that even a little less people will pick up with Hydrogen, so I will publish the Hydrogen development guidelines reflecting learnings through our actual projects.
If you’re going to be developing with Hydrogen, check it out.


Shopify Hydrogen V1 Development Guidelines

Hydrogen's Advantage over Shopify Themes

When creating a Shopify front-end, there are two ways to use the Shopify theme (the WordPress theme and concept is similar: monolith configuration) and Hydrogen. Simply put, if you want to go fast, you can use Liquid or Hydrogen if you want to go far away. It's more difficult to create a site with Hydrogen but it has the following benefits instead:

  1. faster on sites with many dynamic updates
  2. The front end is one, EC parts Shopify and CMS can connect to multiple backends like WordPress
  3. Easier Team Development on Large Sites
  4. SEO is easy because URL structure can be freely determined
  5. Multilingual, easy to cross-border ECs

At the time of writing, there is a V2 based on Shopify’s acquisition of React framework “Remix”, but here we will discuss V1.
V2 is like the Hydorgen V1 component being absorbed into Remix, and learning about it doesn't waste any time you implement it in V2.

What is Hydrogen?

A front-end framework used to build shopify. It is written in React/Typescript and comes with the various components and tools required for EC sites. The feature is the adoption of RSC (React Server Component), which allows server-side updates per component.
Hydrogen overview

Create a new theme

Hydrogen quickstart

Hydrogen says, " Hello World and said, Demo Store There are two starters for each. JavaScript and TypeScript Types are easier to work with, such as the metafield data in shopify.

  • Hello World Minimum Templates
  • Demo Store -> Templates that already implement a single function
yarn create @shopify/hydrogen

Create according to the command instructions.

Since then, create guidelines for using the Demo Store / TS


Environmental settings

yarn / npm / pnpm

It is better not to mix yarn.lock and package-lock.json, so we'll unify it into one of them within the team.

The package.json contains a package manager to use in the field, and the lock file is added to the repository without gitignore.

"packageManager": "yarn@1.22.19",

VSCode

The default setting recommends installing the following VSCode extension:

{
  "recommendations": [
    "graphql.vscode-graphql",
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "bradlc.vscode-tailwindcss"
  ]
}

For Demo Store templates, prettier is included in the initial configuration; if you want to change the formatting of your code within a team, create and configure the prettier config file as appropriate.

ESLint

yarn lint and yarn lint-ts Do a lint check with ESLint settings as appropriate.

// console.*を許可する場合
rules: {
    'no-console': 'off',
}

Vite

as a build tool vite It is adopted.

js will not work in production, so use it basically as the default if you set up a rollup option.

/// <reference types="vitest" />
import {defineConfig} from 'vite';
import hydrogen from '@shopify/hydrogen/plugin';

export default defineConfig({
  plugins: [hydrogen()],
  resolve: {
    alias: [{find: /^~\/(.*)/, replacement: '/src/$1'}],
  },
  optimizeDeps: {
        // このあたりは適宜調整する
    include: ['@headlessui/react', 'clsx', 'react-use', 'typographic-base'],
  },
  test: {
    globals: true,
    testTimeout: 10000,
    hookTimeout: 10000,
    maxThreads: 1,
    minThreads: 1,
  },
});

Node

nodenv node-version, and if you are developing on Windows, you can use .node-version to manage your version nvm Install it instead. volta haha. n I think you may use it.

node-version, it will also apply directly to the node versioning in most deployment environments.

Also specify the node version of theengines in package.json () yarn install The node specified at the time).

17.9.1
"engines": {
  "node": ">=17"
},

shopify collaboration

From the shopify management screen, access to <YOUR_SHOPIFY_DOMAIN.myshopify.com/admin/settings/apps/development> and add a custom app.

Publish an access token for the storefront API and keep your domain name and access tokens in .

hydrogen.config.ts storeDomain and storefrontToken and storefrontApiVersion Rewrite".

In addition, environment variables can be read with hydrogen.config.ts by conditional bifurcation of production and local environmental variables.

Once it works with shopify, you can open GraphiQL explorer in the URL below to see if data is available.

http://localhost:3000/___graphql

query {
  shop {
    name
    description
  }
}

environmental variable

Environment variables can be described in .env, since only the prefix hashed ones can be retrieved by clients (in vite). reference )、VITE_ Put it on.

VITE_SHOPIFY_STORENAME=**********.myshopify.com
VITE_SHOPIFY_STOREFRONT_TOKEN=**********

In the case of Cloudflare Workers, if there are types declared in global, then they will preferentially read the environment variables registered with Cloudflare.

For that reason, create @types/env.d.ts and so on and type declaration as follows:

export {};

declare global {
  const SHOPIFY_STORENAME: string;
  const SHOPIFY_STOREFRONT_TOKEN: string;
}

If there are any environment variables registered in Cloudflare, go read them and if they do not, write a conditional bifurcation on const.

// SHOPIFY_STORENAMEでCloudflareに登録
// VITE_SHOPIFY_STORENAMEでローカルの.envに登録

export const STORE_DOMAIN =
  typeof SHOPIFY_STORENAME === 'string'
    ? SHOPIFY_STORENAME
    : import.meta.env.VITE_SHOPIFY_STORENAME;

This value is used in hydrogen.

import {STORE_DOMAIN} from '~/lib/const';

export default defineConfig({
  shopify: {
    storeDomain: STORE_DOMAIN,

development setting.

Tailwind.css

the default css framework Tailwind.css It is safe to use TW as it is.

Write a CSS Token in src/styles/index.css and write it tailwind.config.js js can be left in the basic initial settings.

in order not to bloat the bundle size @apply It is better to minimize the use of directives.

/* CSS Token */
:root {
  --font-size-display: 3rem;
  --font-size-heading: 2rem;
    --font-size-lead: 1.125rem;
theme: {
    extend: {
            fontSize: {
        display: ['var(--font-size-display)', '1.1'],
        heading: ['var(--font-size-heading)', '1.25'],
        lead: ['var(--font-size-lead)', '1.333'],

asset

SVG inserts as inline code rather than imagesIn addition to being generally an anti-pattern because of the slow rendering, it may not be displayed in a deployed environment.

export function AccountIcon(props: IconProps) {
  return (
    <Icon {...props}>
      <title>Accounts</title>
      <circle cx="20" cy="10.5" r="4.5" strokeWidth="2" />
      <path
        d="M20 19C13.4375 19 9.5 20.2857 9.5 28H30.5C30.5 20.2857 26.5625 19 20 19Z"
        strokeWidth="2"
      />
    </Icon>
  );
}

jpg, png and so on are stored in the asserts folder, but if you have a large file size, add files to the management screen ofshopify and copy and paste url directly will do WebP support or CDN cache.

ico and other files that should be deployed to a root are added in the public folder.

GraphQL

Hydrogenism So, query aims to be available for each component: get all data at the top level and write it directly within each component instead of bucket relaying to a child component.

Where fetch parallelization takes place to avoid network request waterfalls preload: true Set it up.

const {data} = useShopQuery({
  query: QUERY,
  variables: {
    handle: '***',
  },
    preload: true,
});

point of attention in a directory

in hydrogen, each layer index.ts and index.server.ts It is possible to compile the description when importing from other files by exporting components together.

The client component and the shared component index.ts and the server component index.server.ts Described in the article.

Example: Component > Global Substitution

export {CartBadge} from './CartBadge';
export {CartDrawer} from './CartDrawer.client';
export {Drawer} from './Drawer.client';
export {Footer} from './Footer.server';
export {Layout} from './Layout.server';
export {NotFound} from './NotFound.server';

In addition, the global directory is exported together in a component directory.

export * from './global/index';
export * from './global/index.server';

By doing so, you can aggregate and import the components present in various layers.

import {Text, Button, CartBadge, CartDrawer, Section} from '~/components';
import {Header, Footer, NotFound} from '~/components/index.server';

analytics

It integrates with Google Tag Manager and Shopify Analytics.

  1. If you add a GTM, this document. set up according to
  2. If you want to send analytics datato a shopify management screen, this document. set up according to

deploy.

Deploy a Hydrogen storefront

Refer to the above for various deployment configurations. For no particular reason use Shopify genuine hosting Oxygen. If you don't use Oxygen, keep in mind: When Hydrogen first came out there was a time when an RSC component couldn't handle Japanese well and it became garbled, building Docker containers on fly.io and hosting them may have been done, but now that seems to be solved.

Setting up Private Storefront Token

If hydrogen doesn't use Oxygen, Rate Limit measures are mandatory Yes.

The normal Storefront API uses Public Token: delegate access token Use a private token.

delegate access token ha. here. Using the GraphQL Admin or REST Admin API mutation (POST) a token will be issued from the perspective of security. delegateAccessScope It is better to specify the minimum required.

{ "delegate_access_scope": [ "unauthenticated_read_content_entries", "unauthenticated_read_content_models", "unauthenticated_write_checkouts", "unauthenticated_read_checkouts", "unauthenticated_read_product_listings", "unauthenticated_read_product_pickup_locations", "unauthenticated_read_product_tags", "unauthenticated_read_selling_plans", "unauthenticated_write_customers", "unauthenticated_read_customers", "unauthenticated_read_customer_tags", "unauthenticated_read_product_inventory", "unauthenticated_read_content" ] }
{
    "access_token": "shpat_**********"
}

The issued token is hidden in the env. hydrogen.config.ts of privateStorefrontToken You can read it.

Netlify

You need to use Netlify Edge Functions in order for RSC (react server component) to work, but this is still a beta feature and will no longer work with Netlify's password functionality. beta limitation )

Cloudflare

For Cloudflare, this is an environment variable according to the document Add it and keep the values encrypted.

To make it easier to check later, leave the necessary variables in a comment at wrangler.toml as follows:

# The necessary environment variables are:
# - SHOPIFY_STORENAME
# - SHOPIFY_STOREFRONT_TOKEN

Set the deployment command to package.json, and if you don't set up a CI such as github actions then manually hit the delete command.

"scripts": {
    "build": "shopify hydrogen build --entry worker",
    "deploy": "wrangler publish"

Our company's Hydrogen production record

Cryogenic Cookware BONIQ
*Hydrogen V1
atelier yori.so
*Hydrogen V2

article category