#Reading Url from a server component

4 messages · Page 1 of 1 (latest)

slate pawn
#

Hi, I am trying retrieve the value from URLParams into my server component, however , searchParams returns an empty object, I have read and followed Nextjs tutorial doc on it, but it is not working in my application. Here is my code below and i have also attached my app folder directory.

Here is the code in my Search component
"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useDebouncedCallback } from "use-debounce";

const Search = ({ placeholder }) => {
const searchParams = useSearchParams();
const router = useRouter();
const pathname = usePathname();

const handleSearch = useDebouncedCallback((e) => {
const params = new URLSearchParams(searchParams);

if (e.target.value) {
  e.target.value.length > 2 && params.set("q", e.target.value);
} else {
  params.delete("q");
}
router.replace(`${pathname}?${params}`);

}, 300);

return (
<div>
<input type="text" placeholder={placeholder} onChange={handleSearch} />
</div>
);
};

export default Search;

Here is the server component code

import Search from "./search-bar";

const UsersPage = async ({ searchParams }) => {
const q = searchParams?.q || "";

console.log(searchParams, "searchparams");

return (
<div>
<Search placeholder="Search for a user..." />
</div>
);
};

export default UsersPage;

pale fulcrumBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

slate pawn
#

This started happening since i implemented the localisation feature

slate pawn
#

Problem solved by extracting the searchParams in the middleware and passing it to the Next Response Url

export function middleware(request) {

const {
nextUrl: { search },
} = request;
const urlSearchParams = new URLSearchParams(search);
const params = Object.fromEntries(urlSearchParams.entries());

const urlParams = "?" + new URLSearchParams(params);

const pathname = request.nextUrl.pathname;

const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(/${locale}/) && pathname !== /${locale}
);

if (pathnameIsMissingLocale) {
const locale = getLocale(request);
if (locale === i18n.defaultLocale) {
return NextResponse.rewrite(
new URL(
/${locale}${ pathname.startsWith("/") ? "" : "/" }${pathname}${urlParams},
request.url
)
);
}
return NextResponse.redirect(
new URL(
/${locale}${ pathname.startsWith("/") ? "" : "/" }${pathname}${urlParams},
request.url
)
);
}
}