1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS ECS 上の Route Handlers が毎回同じレスポンスを返す問題

Posted at

問題の内容

ECS 上に Next.js を設置し、Route Handlers を使って AWS の別サービスにリクエストを投げ、そのレスポンスをクライアント(ブラウザー)に返すようにしていました。

ちょうど Route Handlers が API の中継サーバーのような格好になっています。

しかし ECS 上にデプロイした直後はちゃんと動くのですが、しばらくするとデータが取れない問題が発生しました。
Route Handler は 200 OK を返すので内部でエラーが発生しているわけではなく、単純にバックエンド(AWS の他のサービス)からデータが取れていないような感じです。

この問題に丸一日悩み、やっと解決したので記録を残しておきます。

結論

Route Handlers が静的コンテンツとしてプリレンダリングされていたのが原因でした。

ファイルの先頭に以下を付けたら解決しました。

export const dynamic = 'force-dynamic'

もうちょっと説明

Route Handlers が prerender されるなんてあるのかと思ったのですが、レスポンスが毎回同じ内容になると判断されるとそうなるみたいです。

私の場合には引数なしだったのが災いして、毎回同じと判断され、静的コンテンツとしてプリレンダリングされてしまったようです。

解決方法としては export const dynamic = 'force-dynamic' を付けて強制的に毎回レンダリング(?)してやるのが良さそうです。

export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'

export const GET = async () => {
  return NextResponse.json({ message: 'OK' })
}

判定方法

ビルドしてやると Static か Dynamic かが分かります。
以下の例だと /api/books が Static になってしまっています。

Route (app)                              Size     First Load JS
┌ ○ /                                    135 kB          219 kB
├ ○ /_not-found                          882 B          85.2 kB
├ λ /api/users                           0 B                0 B
└ ○ /api/books                           0 B                0 B
+ First Load JS shared by all            84.3 kB
  ├ chunks/69-87d8c82a62e1ee09.js        29 kB
  ├ chunks/fd9d1056-c8811681137251ad.js  53.4 kB
  └ other shared chunks (total)          1.9 kB


○  (Static)   prerendered as static content
λ  (Dynamic)  server-rendered on demand using Node.js
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?