LoginSignup
11
4

More than 1 year has passed since last update.

Next.js getServerSidePropsとgetStaticProps Docker環境のAPIにアクセスできない

Posted at

起こったエラー

DockerでNext.jsとLaravelの環境を構築

getServerSidePropsgetStaticPropsのメソッドの中でLaravelで作成したapiにアクセスしてデータを取得しようとしたところコネクションエラーが発生した。

export const getServerSideProps = async () => {
    const res = await fetch('http://localhost:8080/api/users')
    const data = await res.json()

    return { props: { data } }
}

このように記述をして全然データ取得が出来ませんでした。

試しにuseEffectの中で同じエンドポイントのhttp://localhost:8080/api/usersにデータを取得しに行ったところ問題なく取得できました。
useEffectの中では出来てなぜ出来ないのか分からず、getServerSidePropsの書き方がおかしいのではないかと思い軽く合計で5〜6時間は葛藤しました。

解決策はgetServerSidePropsgetStaticPropsの中でデータを取得する場合はlocalhost:8080ではなくて、nginx:80にすることでした。

export const getServerSideProps = async () => {
    const res = await fetch('http://nginx:80/api/users')
    const data = await res.json()

    return { props: { data } }
}

このようにしたら取得できました。
dockerの構成はこんな感じです。

docker-compose.yml
nginx:
  container_name: nginx
 ports:
  - 8080:80

一応解決はできたけど、自分の中でこの現象を完全に理解しきれていないのでもう少し勉強します。
Dockerもちゃんと勉強したい....

参考

https://zenn.dev/shimotaroo/scraps/a782c20d602070

11
4
2

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
11
4