Next.js Discord

Discord Forum

searchParams not working, for me atleast

Answered
Pyr0Lover posted this in #help-forum
Open in Discord
I have tried in different pages to just log a searchParam. But i either get undefined, or empty object...

export default async function Page({
params: { lang },
searchParams,
}: {
params: { lang: Locale };
searchParams?: any;
}) {
console.log('params:', searchParams);

If I go to /?abc=123

It prints this: "params: {}"

Am i missing something? I have tried everything I've seen so far
Answered by joulev
const searchParams = request.nextUrl.searchParams.toString();
const path = `${pathname}${searchParams.length > 0 ? `?${searchParams}` : ""}`;
View full answer

10 Replies

Tried this, but on the map page:

https://www.reddit.com/r/nextjs/comments/1d53tra/searchparams_in_server_component/

I get 'undefined'. Not sure what's going on since these are both server components
Ahhh I figured the issue is with the internationalization middleware code:


// export function middleware(request: NextRequest) {
// const pathname = request.nextUrl.pathname;
// const pathnameIsMissingLocale = i18n.locales.every(
// (locale) =>
// !pathname.startsWith(/${locale}/) && pathname !== /${locale},
// );

// // Redirect if there is no locale
// if (pathnameIsMissingLocale) {
// const locale = getLocale(request);
// const url = new URL(
// /${locale}${pathname.startsWith('/') ? '' : '/'}${pathname},
// request.url,
// );

// if (locale === i18n.defaultLocale) {
// return NextResponse.rewrite(url);
// }
// return NextResponse.redirect(url);
// }
// }


Not sure why tho?
Japanese Bobtail
You will need to share mode code here
@Pyr0Lover are you doing default locale rewrites? If not.. it won't work xD
Lemme show how that looks
const locales = ["en"];
const defaultLocale = "en";
function getLocale() {
  const headers = { "accept-language": "en-US,en;q=0.5" };
  const languages = new Negotiator({ headers }).languages();

  const currentLocale = match(languages, locales, defaultLocale);

  return currentLocale;
}

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (!pathnameHasLocale) {
    let locale = getLocale();
    request.nextUrl.pathname = `/${locale}${pathname}`;
    if (locale === defaultLocale) return NextResponse.rewrite(request.nextUrl);

    return NextResponse.redirect(request.nextUrl);
  }
const searchParams = request.nextUrl.searchParams.toString();
const path = `${pathname}${searchParams.length > 0 ? `?${searchParams}` : ""}`;
Answer
@joulev In the place where you declare the new url, you need to add the search params also
Yup, the searchParams were not being passed with this middleware. Thank you for helping