🔍

パスパラメータ・クエリパラメータの取得

2023/12/14に公開

Next.jsでパスパラメータとクエリパラメターの取得方法が毎回わからなくなる。
忘れないように備忘録

サーバーサイドで取得する場合

http://localhost:3000/post/1234?key=value&msg=hello&msg=bye にアクセスした場合

app/post/[id]/page.tsx
const page = ({
  params,
  searchParams,
}: {
  params: { id: string };
  searchParams: { [key: string]: string | string[] | undefined };
}) => {

  // パスパラメータ
  console.log({ params }); // => params: { id: '1234' }
  
  // クエリパラメータ
  console.log(searchParams); // => { key: 'value', msg: [ 'hello', 'bye' ] }
  
  // querymsg の型は const msg: string | string[] | undefined
  const querymsg = searchParams.msg;
  return <div>page</div>;
};
if (typeof querymsg === "string") {
  // string型の場合の処理
  
}
if (Array.isArray(querymsg)) {
  // string[]型の場合の処理
}

特定のクエリパラメータを取得する場合

const page = ({
  params,
  searchParams,
}: {
  params: { id: string };
  searchParams: { key?: string | string[]; msg?: string | string[] };
}) => {
  console.log({ key: searchParams.key, msg: searchParams.msg });
  // { key: 'value', msg: [ 'hello', 'bye' ] }
  return (
    <div>
      <Component />
    </div>
  );
};

クライアントサイドで取得する場合

同じようにhttp://localhost:3000/post/1234?key=value&msg=hello&msg=bye にアクセスした場合

"use client";

import { usePathname, useSearchParams } from "next/navigation";
import React from "react";

export const Component = () => {
  // クエリパラメータの取得
  const searchParams = useSearchParams();
  const msg = searchParams.get("msg");
  const msgAll = searchParams.getAll("msg");

  console.log({ code: msg, all: msgAll });
  // msg => "hello", msgAll => ["hello", "bye"]
  
  // パスパラメータの取得
  const pathname = usePathname();
  console.log(pathname); // pathname => /post/1234

  return <div>Component</div>;
};

Discussion