Search code examples
next.jsnext-router

Next.js 14 App Router - router.push ignores the searchParams


I'm using Next.js 14.1.4 and I have a <form> in client component with <input>. Submitting triggers a function that should redirect the user to the search result page with proper query in the URL. The problem is that the query itself is cut off - at least in most of the cases.

I've tried all the workarounds I found online, but nothing worked - most of them are for Pages Router :/

Client component:

"use client";
import { useRouter } from "next/navigation";

const Navbar = (props) => {
    const inputRef = useRef(null);
    const router = useRouter();

    const handleSubmit = (e) => {
        e.preventDefault();
        setIsSearchOpen(false);
        router.push("/search/?query=${encodeURIComponent(inputRef.current?.value)}`);
    };

    return (
        <nav>
        // lot of not important code
            <form onSubmit={handleSubmit} className="relative w-full mx-40">
                <input className="w-full outline-none" ref={inputRef} />
                <button className="absolute right-0 bottom-0 h-4 w-4 bg-primary" type="submit" />
            </form>
        </nav>
    );
};

export default Navbar;

If I console.log the url it looks as expected, but the redirect lands on https://fakedomain.com/search

What is weird, if I will remove the initial / from the router.push() string, it works, but get wrong redirects when triggered from other path than basePath.

The server-side component page is quite simple - it reads the searchParams from props and fetches the data based on the searchParams, but it's undefined if it's not passed to URL. The page works fine when query is added manually into address bar.

const page = async (props) => {
    const { searchParams, params } = props;
    console.log(searchParams); //undefined

    //dealing with the searchParams logic

    return (
        // returning the results
};

export default page;

Solution

  • Thank You for trying to help me Guys. I figured it out - a newbie mistake. It wasn't the issue within the Next router - it was my i18n middleware responsible for cutting out the searchParams.

    Thanks again and case closed :)

    P.S. I feel like an idiot now ;p