LoginSignup
15
2

More than 3 years have passed since last update.

Nextでnext devなら動くのにnext buildでエラーが出て解決した

Last updated at Posted at 2020-10-22

前提

  • NextでWEBページindex.jsとDB接続用のAPIget-data.jsを定義
  • index.jsgetStaticPropsget-dataAPIを叩いていた
index.js
import fetch from "node-fetch"

export async function getStaticProps({ params }) {
  // getStaticPropsでget-dataAPIを叩く
  const res = await fetch("http://localhost:3000/api/get-data")
  const data = await res.json()
  return { props: { data } }
}

export default function Index({ data }) {
  ...省略
}
api/get-data.js
export default async (req, res) => {
  // DB接続してデータ取得
  const data = await getData()
  res.status(200).json(data)
}

現象

  • next devだと問題は発生せず、期待通り動いたのですが…
  • next buildだと以下のようなエラーが発生しました
$ next build
...省略
Compiled successfully.

Automatically optimizing pages ..
Error occurred prerendering page "/index". Read more: https://err.sh/next.js/prerender-error:
FetchError: request to http://localhost:3000/api/get-data failed, reason: connect ECONNREFUSED 127.0.0.1:3000

解決策

stack overflowにそのまんまな事象と解決策があったので参考にしました
https://stackoverflow.com/questions/61452675/econnrefused-during-next-build-works-fine-with-next-dev

公式ドキュメントに記載してある通り、

You should not fetch an API route from getStaticProps — instead, you can write the server-side code directly in getStaticProps.

とのことなのでgetStaticPropsでAPIルートを呼んではいけないようです。
getStaticPropsはサーバサイド処理のため、APIで実行したい処理をそのままかけ、ということでした。

変更後

index.js
export async function getStaticProps({ params }) {
  // getStaticPropsでDB接続してデータ取得
  const data = await getData()
  return { props: { data } }
}

export default function Index({ data }) {
  ...省略
}

get-data.jsは不要になったため削除しました

ふりかえり

next devだと問題ないのにnext buildだとエラーが発生する意味がわからなく、ポートを固定したのがよくなかったのか?とかbuildで外部APIの接続確認を行っているオプションを外せないか?などかなりはまってしまいました。。解決してよかったです。

そもそもgetStaticPropsはビルド時にサーバサイド側で走る処理なので、DB接続があるからといってAPIを経由する必要はありませんでした。DB処理をAPI側にまとめたいと思って余計なことをしていました…。ドキュメントちゃんと読め、という話ですね。。反省…

15
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
2