Open14

読者コミュニティ|Next.jsとStripeではじめるシンプルなECサイト開発ワークショップ

「04 Next.jsでAPIやサーバー側処理のあるサイトを作ってみよう」の最後の箇所で「npx next start -p 3100」を実行したところ、下記エラーが発生しました。どのようにすればエラーが回避できるでしょうか?

% npx next start -p 3100                                                                                                                  [main]:+
ready - started server on 0.0.0.0:3100, url: http://localhost:3100
Error: Could not find a production build in the '/Users/hamez/_pj/nextjs-stripe-ec/.next' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id
    at NextNodeServer.getBuildId (/Users/hamez/_pj/nextjs-stripe-ec/node_modules/next/dist/server/next-server.js:139:23)
    at new Server (/Users/hamez/_pj/nextjs-stripe-ec/node_modules/next/dist/server/base-server.js:90:29)
    at new NextNodeServer (/Users/hamez/_pj/nextjs-stripe-ec/node_modules/next/dist/server/next-server.js:86:9)
    at NextServer.createServer (/Users/hamez/_pj/nextjs-stripe-ec/node_modules/next/dist/server/next.js:109:16)
    at async /Users/hamez/_pj/nextjs-stripe-ec/node_modules/next/dist/server/next.js:121:31

Error: Could not find a production build in ~'.next' directory.については、npx next buildを実行してから再実行することで解決できます。

ありがとうございます!「npx next build」でエラー無くなりました。

06 の 「jqを利用して整形した実行結果の例」で、
curl http://localhost:3000/api/products | jq .
を実行したのですが、
zsh: command not found: jq
が帰ってきて商品一覧が表示されません。

すみません。jqありきの説明が途中で混ざっていますね・・・
curl http://localhost:3000/api/products で文字列が大量に表示されれば、動作確認としてはOKです。

macの場合は、brew install jqでインストールできます。

06の下記コマンドを実行したところ、下記エラーになりました。

% curl http://localhost:3000/api/products                                                                                                 [main]:+
wait  - compiling /api/products...
wait  - compiling...
event - compiled client and server successfully in 110 ms (426 modules)
error - Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.
wait  - compiling /_error (client and server)...
wait  - compiling...
event - compiled client and server successfully in 87 ms (427 modules)
<!DOCTYPE html><html><head><style data-next-hide-fouc="true">body{display:none}</style><noscript data-next-hide-fouc="true"><style>body{display:block}</style></noscript><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><meta name="next-head-count" content="2"/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills.js?ts=1650607714161"></script><script src="/_next/static/chunks/webpack.js?ts=1650607714161" defer=""></script><script src="/_next/static/chunks/main.js?ts=1650607714161" defer=""></script><script src="/_next/static/chunks/pages/_app.js?ts=1650607714161" defer=""></script><script src="/_next/static/chunks/pages/_error.js?ts=1650607714161" defer=""></script><script src="/_next/static/development/_buildManifest.js?ts=1650607714161" defer=""></script><script src="/_next/static/development/_ssgManifest.js?ts=1650607714161" defer=""></script><script src="/_next/static/development/_middlewareManifest.js?ts=1650607714161" defer=""></script><noscript id="__next_css__DO_NOT_USE__"></noscript></head><body><div id="__next"></div><script src="/_next/static/chunks/react-refresh.js?ts=1650607714161"></script><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{"__NEXT_PAGE":"/api/products"},"buildId":"development","isFallback":false,"err":{"name":"Error","message":"You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.","stack":"Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.\n    at res.toJSON.then.StripeAPIError.message (/Users/hamez/_pj/nextjs-stripe-ec/node_modules/stripe/lib/StripeResource.js:214:23)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)"},"gip":true,"scriptLoader":[]}</script></body></html>%                                             

.env.local ファイルの作成場所等に問題がありますか。

% ls nextjs-stripe-ec/.env.local 
nextjs-stripe-ec/.env.local
Hidden comment

環境変数をNext.jsが読み込めていない様子ですので、一度npx next devを停止して再実行していただけますでしょうか?

「npx next start」が起動していたので、そちらを停止/再実行しましたが、同様のエラーが出力されているようです。

% jobs
[1]  - running    npm run dev
[2]  + running    npx next start -p 3100

# 上記「npx next start -p 3100」を停止

% npx next start -p 3100 &
[2] 12757

% curl http://localhost:3000/api/products
error - Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.
<!DOCTYPE html><html><head><style data-next-hide-fouc="true">body{display:none}</style><noscript data-next-hide-fouc="true"><style>body{display:block}</style></noscript><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><meta name="next-head-count" content="2"/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills.js?ts=1650608864866"></script><script src="/_next/static/chunks/webpack.js?ts=1650608864866" defer=""></script><script src="/_next/static/chunks/main.js?ts=1650608864866" defer=""></script><script src="/_next/static/chunks/pages/_app.js?ts=1650608864866" defer=""></script><script src="/_next/static/chunks/pages/_error.js?ts=1650608864866" defer=""></script><script src="/_next/static/development/_buildManifest.js?ts=1650608864866" defer=""></script><script src="/_next/static/development/_ssgManifest.js?ts=1650608864866" defer=""></script><script src="/_next/static/development/_middlewareManifest.js?ts=1650608864866" defer=""></script><noscript id="__next_css__DO_NOT_USE__"></noscript></head><body><div id="__next"></div><script src="/_next/static/chunks/react-refresh.js?ts=1650608864866"></script><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{"__NEXT_PAGE":"/api/products"},"buildId":"development","isFallback":false,"err":{"name":"Error","message":"You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.","stack":"Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.\n    at res.toJSON.then.StripeAPIError.message (/Users/hamez/_pj/nextjs-stripe-ec/node_modules/stripe/lib/StripeResource.js:214:23)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)"},"gip":true,"scriptLoader":[]}</script></body></html>%

http://localhost:3000/npm run devのほうを再実行させないとです。

npx next start -p 3100でスタートしているアプリは、http://localhost:3100/ ですね。
また、npx next startの方に更新を反映させるためには、npx next buildも実行する必要があります、

09 の「APIをアプリに組み込もう」で

<form action="/api/checkout_session" method="POST">
                              <input type='hidden' name='price' value={price.id}/>
                              <input type='hidden' name='quantity' value={1}/> 
                              <Button type='submit'>いますぐ注文する</Button>
                            </form>

に書き換えたところ
「今すぐ注文する」のボタンを押すと

http://localhost:3000/api/checkout_session
に遷移し下記のように表示されてしまいます。
{"id":"cs_test_a1VepRRes1oytOVe7gv5kFO2s8Z3RCEgGhdItCwLSX5YqrBqsCyRWatVwc","object":"checkout.session","after_expiration":null,"allow_promotion_codes":null,"amount_subtotal":100,"amount_total":100,"automatic_tax":{"enabled":false,"status":null},"billing_address_collection":null,"cancel_url":"http://localhost:3000/","client_reference_id":null,"consent":null,"consent_collection":null,"currency":"jpy","customer":null,"customer_creation":"always","customer_details":null,"customer_email":null,"expires_at":1650696338,"livemode":false,"locale":null,"metadata":{},"mode":"payment","payment_intent":"pi_3KrGFLLfNcyBUaEb26Nfz19I","payment_link":null,"payment_method_options":{},"payment_method_types":["card"],"payment_status":"unpaid","phone_number_collection":{"enabled":false},"recovered_from":null,"setup_intent":null,"shipping":null,"shipping_address_collection":null,"shipping_options":[],"shipping_rate":null,"status":"open","submit_type":null,"subscription":null,"success_url":"http://localhost:3000/success","total_details":{"amount_discount":0,"amount_shipping":0,"amount_tax":0},"url":"https://checkout.stripe.com/pay/cs_test_a1VepRRes1oytOVe7gv5kFO2s8Z3RCEgGhdItCwLSX5YqrBqsCyRWatVwc#fidkdWxOYHwnPyd1blpxYHZxWjA0TndAYVdJY0tmfEdQZEBnMV9nMn8wTGxtcElxc3BRYzdpMHE0cW53aHNRMDE9MTVPSlFTU3NAZFw2Uk1tUH9kNV1VTjRuSXFNVmMwdkZMNFNwPEhNUjNWNTVCTUY0VTZOUScpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl"}

「作成した決済ページにリダイレクトしよう」ステップのコード変更が保存できていないかもしれません。
データがそのまま表示されるのは、res.status(200).json(session)が実行されているからの可能性が高いです。
res.redirect(301, session.url)で保存できていればリダイレクトしますので、一度確認をお願いします。

https://zenn.dev/stripe/books/stripe-nextjs-use-shopping-cart/viewer/step4-2_checkout_session#作成した決済ページにリダイレクトしよう
ログインするとコメントできます