Next.js Discord

Discord Forum

How can I use import { NextRouter } from 'next/router'; in App router?

Answered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I am trying to use it in an interface like this: router: NextRouter;
setRouter: (router: NextRouter) => void;

Also get this error
Argument of type 'AppRouterInstance' is not assignable to parameter of type 'NextRouter'.
Type 'AppRouterInstance' is missing the following properties from type 'BaseRouter':

When using next/navigation useRouter

export const Notebook = () => {
const router = useRouter();

useNotebookHotkeys();
useNotebookStore.getState().setRouter(router);
useEffect(() => {
initializePosthog();
}, []);


Is there an AppRouterInstance that I can use as a drop in replacement to be used with interfaces?
Answered by joulev
nextjs doesn't export a type for that. you can do
import type { useRouter } from "next/navigation";
export type Router = ReturnType<typeof useRouter>;

and use this Router type.
View full answer

6 Replies

What are you trying to do lol @Barbary Lion why you tryna interface it
Barbary LionOP
Trying to migrate an old code base and hoping I dont have to rewrite it lol
No but what are you trying to do.. like functionality @Barbary Lion
Answer
if you want to get the type without having to declare a new type,
import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { useRouter } from "next/navigation";

const router: AppRouterInstance = useRouter();
Barbary LionOP
That worked thank you!