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?

App Router dynamic routing時のparamsエラーの対応

Last updated at Posted at 2025-06-18

これは何?

Next.jsのApp Routerにて、dynamic routingページでSSRをしたかった時のエラー対応メモです。

dynamic routing?
app/[id]/page.js ⬅︎こういうのです

paramsをそのまま使用するとエラー

以下のように SSR の中で params.id を直接参照すると、エラーになりました。

export default async function UserProfile({ params }: {params : {id: string}}) {
  const id = params.id; // ここでエラー
  let profile = null;
  try {
    const res = await apiClient.get(`profile/${id}`);
    profile = res.data;
  ...

出たエラーはこちら

Error: Route "/profile/[id]" used `params.id`. `params` should be awaited before using its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis
    at UserProfile (src/app/profile/[id]/page.tsx:10:20)

要するに、paramsはPromiseになっているので、awaitが必要とのこと。(そうなんだ)

Next.js 公式ドキュメントを読む

サンプルソースに対応の方法が記述されていました。
Dynamic APIs are Asynchronous

// サンプル引用
async function Page({ params }) {
  // asynchronous access of `params.id`.
  const { id } = await params
  return <p>ID: {id}</p>
}

エラーを修正する

型定義も、わかりやすくtypeに切り出してしまいましょう!


type PageProps = {
  params: { id: string }
};

export default async function UserProfile({ params }: PageProps) {
  const { id } = await params; 
  let profile = null;
  try {
    const res = await apiClient.get(`profile/${id}`);
    profile = res.data;
  ...

これで無事に動作しました!

所感

もちろんドキュメントを先に読むのも大切ですが、
実際に手を動かしてエラーと向き合いながら学ぶほうが、理解が深まりますね!!

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?