LoginSignup
1
0

AppRouter の server side で path query や search params を取得する方法

Last updated at Posted at 2024-03-30

背景

App Router になってから、 server side での pathQuerysearchParams の取得方法が変わった.

client side なら

import {useSearchParams} from "next/navigation

で済むのだが、 server 側がわからずちょっと詰まった

解決方法 と 実装例

Next.js は page から default で排出された module に対して props を渡している.
この props は Next.js が用意した型定義はなく, 実装者が自前で実装する

// /app/[id]/page.tsx

interface Props {
  params: Record<"id", string>;
  searchParams: Record<string, string | string[] | undefined>
}

export default function Page(props: Props) {
  const {id} = props.params;

  return (
    <main>
       ...
    </main>
  );
}

Next.js 公式 (これをなかなか見つけられなかった)
https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional


抽象度を高めて型定義するなら

interface NextPageProps<T extends string = never> {
  params: Record<T, string>;
  searchParams: Record<string, string | string[] | undefined>
}

// 利用例
type Props = NextPageProps<'id'>;

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