Currently, I am working on a project using Next.js (version 14) that involves implementing a product search feature. The search functionality is managed by a Search component, and the key code snippet is shown below:
// Search component in Search.tsx
"use client";
import { useSearchParams, usePathname, useRouter } from "next/navigation";
import { useDebouncedCallback } from 'use-debounce';
export default function Search({ placeholder }: { placeholder: string }) {
const searchParams = useSearchParams();
const pathname = usePathname();
const { replace } = useRouter();
const handleSearch = useDebouncedCallback((term) => {
const params = new URLSearchParams(searchParams || '');
if (term) {
params.set('q', term);
} else {
params.delete('q');
}
replace(`${pathname}?${params.toString()}`);
}, 300);
return (
<div className="relative">
<input
className="peer block mt-0 w-full rounded-md border border-gray-200 py-[9px] pr-10 text-sm outline-2 placeholder:text-gray-500"
placeholder={placeholder}
onChange={(e) => {
handleSearch(e.target.value);
}}
defaultValue={searchParams?.get('q')?.toString()}
/>
</div>
);
}
In the GET handler within my API route (app/api/products/route.ts), I am attempting to retrieve the query parameter from the URL as follows:
// app/api/products/route.ts
import { NextRequest, NextResponse } from "next/server";
export const GET = async (req: NextRequest) => {
const { searchParams } = req.nextUrl;
const query = searchParams.get("q");
console.log(query);
return NextResponse.json({ query });
};
However, despite updating the URL correctly to /products?q=test+search+product when testing with the input "test search product," the query parameter in the response always returns as null instead of "test search product" as expected. I intend to utilize this query parameter for fetching data from the API with Prisma. Any insights or suggestions on resolving this issue would be greatly appreciated. Thank you!