SaaS / FaaSShopify

ShopifyのHygrogenでJamstackなECサイトをセットアップする方法と、起動時のエラー対処方法メモ

この記事は、Shopify Advent Calendar 2021の19日目の記事です。 なかなか触れなかったHydrogenをようやく触れました。が、自分のECサイト(デモ用)を繋ぎ込んだときにいくつかエラーを踏みま […]

広告ここから
広告ここまで

この記事は、Shopify Advent Calendar 2021の19日目の記事です。

なかなか触れなかったHydrogenをようやく触れました。が、自分のECサイト(デモ用)を繋ぎ込んだときにいくつかエラーを踏みましたので、それを紹介します。

Hydrogenでのアプリセットアップ

Hydrogenでのアプリ作成は、npxコマンドで行います。

% npx create-hydrogen-app

実行すると、プロジェクト名を聞かれます。

これがディレクトリ名になりますので、CamelCase / snake_caseなど、好みのフォーマットで指定しましょう。

? Project name: › first-hydrogen 
Scaffolding Hydrogen app in /Users/sandbox/first-hydrogen…
 Done. Now:
 Update first-hydrogen/shopify.config.js with the values for your storefront. If you want to test your Hydrogen app using the demo store, you can skip this step.
 and then run:

 cd first-hydrogen
   npm install --legacy-peer-deps
   npm run dev

作成後は、完了メッセージにあるように、「ディレクトリに移動して、npm installしてライブラリをインストール。そのあとnpm run devで開発サーバー起動」という手順を踏みます。

vite v2.7.3 dev server running at:
   Local: http://localhost:3000/
   Network: use --host to expose 
 ready in 658ms.

ちなみに余談ですが、npm run devnpx viteでも同じように動かせます。起動時の設定を変更したい場合は、viteのヘルプを見てオプションを追加するとよさそうです。

% npx vite --help
 vite/2.7.3
 Usage:
   $ vite [root]
 Commands:
   [root]           
   build [root]     
   optimize [root]  
   preview [root]   
 For more info, run any command with the --help flag:
   $ vite --help
   $ vite build --help
   $ vite optimize --help
   $ vite preview --help
 Options:
   --host [host]           [string] specify hostname 
   --port            [number] specify port 
   --https                 [boolean] use TLS + HTTP/2 
   --open [path]           [boolean | string] open browser on startup 
   --cors                  [boolean] enable CORS 
   --strictPort            [boolean] exit if specified port is already in use 
   --force                 [boolean] force the optimizer to ignore the cache and re-bundle 
   -c, --config      [string] use specified config file 
   --base            [string] public base path (default: /) 
   -l, --logLevel   [string] info | warn | error | silent 
   --clearScreen           [boolean] allow/disable clear screen when logging 
   -d, --debug [feat]      [string | boolean] show debug logs 
   -f, --filter    [string] filter debug logs 
   -m, --mode        [string] set env mode 
   -h, --help              Display this message 
   -v, --version           Display version number 

shopify.config.jsを更新して、自身のサイトを表示する

Update first-hydrogen/shopify.config.js with the values for your storefront.

プロジェクト作成時に上のようなメッセージが表示されていました。これは、「自分のサイトを表示したい場合、このファイルを更新してね」という意味です。ファイルを見ると、デモサイトの情報が入力されています。

export default {
  locale: 'en-us',
  storeDomain: 'hydrogen-preview.myshopify.com',
  storefrontToken: '3b580e70970c4528da70c98e097c2fa0',
  graphqlApiVersion: 'unstable',
};

Shopify管理画面から、ストアフロントAPIの情報を取得し、上記のファイルの値を書き換えましょう。設定方法は、この記事がわかりやすいと思います。

shopify.config.jsを更新した後、改めてnpm run devを実行すると、サイトのデータが更新されます。

npm run devがエラーになる場合に考えられる原因と対応

Case 1: Token間違え

設定や入力する値を間違えると、npm run devがエラーで中断します。

TypeError: Cannot read properties of null (reading '0')
     at Layout (/src/components/Layout.server.jsx:100:32)
     at renderWithHooks (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:5166:16)
     at renderIndeterminateComponent (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:5251:15)
     at renderElement (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:5433:7)
     at renderNodeDestructive (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:5577:11)
     at retryTask (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:5927:5)
     at performWork (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:5974:7)
     at Immediate._onImmediate (/Users/okamotohidetaka/sandbox/first-hydrogen/node_modules/react-dom/cjs/react-dom-unstable-fizz.node.development.js:4924:14)
     at processImmediate (node:internal/timers:464:21)

上のようなCannot read properties of nullが複数出ている場合、まずはstorefrontTokenの値が間違っていないかを疑いましょう。自分の場合は、一覧部分に表示されている「APIキー」を入力して遭遇しました。

Case 2: 権限不足

プライベートアプリでストアフロントAPIを有効化する場合、「どの機能を有効にするか」を指定する必要があります。ここで全ての権限を有効化していない場合、以下のようなエラーに遭遇することがあります。

GraphQL Error {
   message: 'Access denied for sellingPlanAllocations field. Required access: unauthenticated_read_selling_plans access scope.',
   locations: [ { line: 143, column: 3 } ],
   path: [
     'collections',
     'edges',
     0,
     'node',
     'products',
     'edges',
     0,
     'node',
     'variants',
     'edges',
     0,
     'node',
     'sellingPlanAllocations'
   ],
   extensions: {
     code: 'ACCESS_DENIED',
     documentation: 'https://shopify.dev/api/usage/access-scopes',
     requiredAccess: 'unauthenticated_read_selling_plans access scope.'
   }
 }
 Error: Access denied for sellingPlanAllocations field. Required access: unauthenticated_read_selling_plans access scope.

ストアフロントのAPI権限を、エラーが出なくなるまで増やせば解消されます。

解消した結果

サイトタイトルと、connected storefrontの表示が切り替わりました。商品データも自分で登録したものに挿し変わっていることが確認できればOKです。

shopify.config.jsを更新しても、npm run devは再実行しなくてOK

これは「Viteすげえな」ってなった部分でもあるのですが、この手のFWでありがちな「configを更新したら、npm run xxxを再実行」が不要です。

storefrontTokenに出鱈目な値を入れて保存すると、勝手に再読み込みしてエラーを吐いてくれます。

GraphQLのAPIバージョンやサイトデータを変更したい場合などで、再実行が不要なのはとても助かるなと思います。

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts