Next.js Discord

Discord Forum

useRouter in component library throws error

Unanswered
Parson Russell Terrier posted this in #help-forum
Open in Discord
Parson Russell TerrierOP
I am currently building a component library for next js. I am using rollup as my build tool. However when I run my application I get the following error:

Error: invariant expected app router to be mounted

has anyone encountered a similar error?

My component looks similar to this:

import { useRouter } from "next/navigation";


export const SubmitButton: React.FC = (props) => {
  const router = useRouter(); // Throws error: Error: invariant expected app router to be mounted
  async function submit() {
    // Post request
    const json = request.json();
    if (json.success) {
      router.push("/page");
    }
  }
  return <button onClick={submit}>{children}</button>;
};

2 Replies

Parson Russell TerrierOP
Alternatively I could redirect from a route handler but that does not seem to work either

from my route handler:
let response = NextResponse.redirect("URL", { status: 302 });

response.cookies.set("cookie", "cookieValue", {
   // Cookie options
});

return response


While a 302 is returned in the network tab the page does not change and no actual redirect occurs. But there is a call to the URL specified which is odd
Is it not possible to return a redirect from a route handler?