pathpida with Next.js App Router: Type-Safe useRouter

Web Engineer

pathpida generates typed path and query helpers ($path.ts) from the pages/ and app/ directories of a Next.js project. The latest version as of December 2026, 0.28.0, supports the App Router without any flag. Because the App Router's useRouter (next/navigation) only accepts strings, a small wrapper that takes the $url().path generated by pathpida turns mistakes in the destination or query into type errors. This post shows code that was actually built and tested with Next.js 16.5, explains when to use Next.js's built-in typedRoutes instead, and keeps the Pages Router version written in 2023 for reference.

Updated December 2026: We added code that types useRouter and useSearchParams from next/navigation for the App Router with Next.js 16.5 + pathpida 0.28.0, added a comparison with typedRoutes (stable since Next.js 15.5), and restored the Pages Router code that was missing from the original post from the GitHub repository.

Versions and prerequisites (December 2026)

ItemDetails
Next.js16.5.0 (latest on npm as of December 2, 2026)
pathpida0.28.0 (released October 3, 2026); also supports Vinext
App Router supportDetects app/ (or src/app/) automatically and generates types; there is no dedicated flag
CLI options--enableStatic (-s), --ignorePath (-p), --output (-o), --watch (-w)
Output locationutils/$path.ts if utils/ exists, otherwise lib/$path.ts (under src/ if you use a src/ layout)
Built-in Next.js alternativetypedRoutes (moved from experimental to stable in Next.js 15.5)

App Router support was added to pathpida in November 2022, so you don't need an option like --appdir. If you have both pages/ and app/, routes from both are output into a single pagesPath.

Why type useRouter with pathpida?

Query and path parameters quickly get messy, and you naturally want to manage them in one place. pathpida, published on GitHub, removes the need to maintain URLs in two places in Next.js, and because query parameters are written explicitly with types, it solves most of this problem.

However, useRouter itself doesn't know about these types, so type assertions still creep into the code, and nothing stops you from leaving out a required parameter in router.push.

So here we build a wrapper around useRouter and give it the type information to solve these problems. The first version in 2023 targeted the Pages Router (next/router); the first half of this post rebuilds it for the App Router (next/navigation), which is now the default.

The repository for the first version is here:

GitHub - gomorepython/pathpida_use_query_wapper
Contribute to gomorepython/pathpida_use_query_wapper development by creating an account on GitHub.

Creating the project and adding pathpida (Next.js 16.5)

Create a project with TypeScript, the App Router and a src/ directory.

npx create-next-app@latest next-app --ts --app --src-dir --no-tailwind --eslint --import-alias "@/*" --use-npm --yes
cd next-app
npm install -D pathpida npm-run-all2

The pathpida README uses npm-run-all to run the dev server and watch mode in parallel; here we used npm-run-all2, which provides the same run-p command. Change the scripts in package.json as follows.

{
  "scripts": {
    "dev": "run-p dev:*",
    "dev:next": "next dev",
    "dev:path": "pathpida --ignorePath .gitignore --watch",
    "build": "pathpida --ignorePath .gitignore && next build",
    "start": "next start"
  }
}

We confirmed that adding a page while npm run dev is running regenerates $path.ts automatically (--watch). Running pathpida before build as well means CI never builds with a stale file.

The next.config.ts generated by these steps contained cacheComponents: true. With this setting, next build fails unless components that read params or searchParams are wrapped in <Suspense> (handled in the page.tsx below).

App Router: defining the query type on a page

pathpida reads types exported from page.tsx under the name Query (required query) or OptionalQuery (optional query). We create a /posts/[id] page that takes tab (required) and page (optional).

import { Suspense } from "react";
import { PostDetail } from "./PostDetail";

// pathpida reads this type and makes $url(/engineer/455/{ query }) required
export type Query = {
  tab: "comments" | "history";
  page?: number;
};

async function PostContent({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  return <PostDetail id={id} />;
}

export default function Page({ params }: PageProps<"/posts/[id]">) {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <PostContent params={params} />
    </Suspense>
  );
}

PageProps<"/posts/[id]"> is a global type helper that Next.js generates automatically; you can use it without an import. Running npx pathpida --ignorePath .gitignore generated this pagesPath in src/lib/$path.ts (the buildSuffix function at the top is omitted).

export const pagesPath = {
  'about': {
    $url: (url?: { hash?: string }) => ({ pathname: '/about' as const, hash: url?.hash, path: `/about${buildSuffix(url)}` })
  },
  'posts': {
    _id: (id: string | number) => ({
      $url: (url: { query: Query_1rbok3d, hash?: string }) => ({ pathname: '/posts/[id]' as const, query: { id, ...url.query }, hash: url.hash, path: `/posts/${id}${buildSuffix(url)}` })
    })
  },
  $url: (url?: { hash?: string }) => ({ pathname: '/' as const, hash: url?.hash, path: `/${buildSuffix(url)}` })
};

For App Router routes, besides pathname and query, the result includes path with the query string already built (for example /posts/1?tab=comments&page=2). The route group (marketing) is dropped from the URL and output as pagesPath.about.

Because Query is defined, forgetting the query or passing a wrong value is a type error. This is the actual output of tsc --noEmit:

import { pagesPath } from "@/lib/$path";

pagesPath.posts._id(1).$url();
// error TS2554: Expected 1 arguments, but got 0.

pagesPath.posts._id(1).$url({ query: { tab: "comment" } });
// error TS2820: Type '"comment"' is not assignable to type '"comments" | "history"'. Did you mean '"comments"'?

pagesPath.posts._id(1).$url(/engineer/455/{ query: { page: 2 } });
// error TS2741: Property 'tab' is missing in type '{ page: number; }' but required in type 'Query'.

Wrapping useRouter from next/navigation

In the App Router, useRouter is imported from next/navigation and only accepts a string, as in router.push(href: string) (you can't pass a { pathname, query } object as with the Pages Router's next/router). So we write a wrapper that accepts only the return value of pathpida's $url() and passes its path.

"use client";

import type { Route } from "next";
import { useRouter, useSearchParams } from "next/navigation";
import { useMemo } from "react";

type NavigateOptions = Parameters<ReturnType<typeof useRouter>["push"]>[1];

// Accept only the return value of pathpida's $url() (an object with path)
// Cast to Route in case typedRoutes is enabled
type PathpidaUrl = { path: string };

export function useTypedRouter() {
  const router = useRouter();

  return useMemo(
    () => ({
      ...router,
      push: (url: PathpidaUrl, options?: NavigateOptions) =>
        router.push(url.path as Route, options),
      replace: (url: PathpidaUrl, options?: NavigateOptions) =>
        router.replace(url.path as Route, options),
    }),
    [router],
  );
}

// Query values are always strings at runtime: take only the keys from the type, values are string | undefined
export type SearchParamsOf<Q> = { [K in keyof Q]-?: string | undefined };

export function useTypedSearchParams<Q>(): SearchParamsOf<Q> {
  const searchParams = useSearchParams();
  return useMemo(
    () => Object.fromEntries(searchParams.entries()) as SearchParamsOf<Q>,
    [searchParams],
  );
}

Because the argument of push and replace is now { path: string }, you can no longer write a string directly and must always go through pagesPath. as Route is a cast for when typedRoutes (below) is enabled; the code compiles unchanged when it is disabled.

The calling side looks like this. If you forget to pass query to $url(), you get a type error right there.

"use client";

import { pagesPath } from "@/lib/$path";
import { useTypedRouter } from "@/hooks/useTypedRouter";

export function NavButtons() {
  const router = useTypedRouter();

  return (
    <button
      type="button"
      onClick={() =>
        router.push(
          pagesPath.posts._id(1).$url({ query: { tab: "comments", page: 2 } }),
        )
      }
    >
      Go to page 2 of post 1's comments
    </button>
  );
}

<Link> also accepts an object for href, so you can pass the return value of $url() directly. In the built HTML it was output as <a href="/about">.

import Link from "next/link";
import { pagesPath } from "@/lib/$path";
import { NavButtons } from "./NavButtons";

export default function Home() {
  return (
    <main>
      <Link href={pagesPath.about.$url()}>About</Link>
      <NavButtons />
    </main>
  );
}

Reading useSearchParams with types

On the destination page, read the query with useSearchParams(). As noted in the conclusion of the first version, a query value may be typed as number or boolean, but at runtime it is always a string. So the hook takes only the key names from the Query type and returns values as string | undefined (useTypedSearchParams above). If you need a number, convert it on the calling side.

"use client";

import { useTypedSearchParams } from "@/hooks/useTypedRouter";
import type { Query } from "./page";

export function PostDetail({ id }: { id: string }) {
  const { tab, page } = useTypedSearchParams<Query>();
  const pageNumber = Number(page ?? "1"); // convert it yourself if you need a number

  return (
    <div>
      <p>id: {id}</p>
      <p>tab: {tab ?? "(none)"}</p>
      <p>page: {pageNumber}</p>
    </div>
  );
}

A typo in a key is a type error, and values are forced to be treated as strings, so you never get the mismatch of "the type says number but the value is actually "2"".

Testing it

With npm run build, /posts/[id] was built as a Partial Prerender (a static shell plus a dynamically streamed part).

Route (app)
┌ ○ /
├ ○ /_not-found
├ ○ /about
└   /posts/[id]
  └ ◐ /posts/[id]

We started the app with npm start, clicked the button on the home page in headless Chromium, and confirmed that it navigated to http://localhost:4790/posts/1?tab=comments&page=2 and showed "id: 1 / tab: comments / page: 2".

How it differs from Next.js's built-in typedRoutes

Next.js has a built-in typedRoutes option that makes links to non-existent paths a type error. It appeared as a beta in Next.js 13.2 and became stable in Next.js 15.5, moving from experimental.typedRoutes to typedRoutes (with Turbopack support).

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  typedRoutes: true,
};

export default nextConfig;

We enabled it in the same project, generated the types with next typegen, and ran the following component through tsc --noEmit.

"use client";

import type { Route } from "next";
import Link from "next/link";
import { useRouter } from "next/navigation";

export function TypedRoutesDemo({ id }: { id: number }) {
  const router = useRouter();
  const dynamic = "/posts/" + id;
  return (
    <>
      <Link href="/about">About</Link>
      <Link href={`/posts/${id}?tab=comments`}>Comments</Link>
      <Link href="/abuot">typo</Link>
      <button type="button" onClick={() => router.push("/posts/1")}>push</button>
      <button type="button" onClick={() => router.push(dynamic)}>push2</button>
      <button type="button" onClick={() => router.push(dynamic as Route)}>push3</button>
    </>
  );
}
src/app/TypedRoutesDemo.tsx(14,13): error TS2820: Type '"/abuot"' is not assignable to type 'UrlObject | RouteImpl<"/abuot">'. Did you mean '"/about"'?
src/app/TypedRoutesDemo.tsx(16,56): error TS2345: Argument of type 'string' is not assignable to parameter of type 'RouteImpl<string>'.

Only the non-existent /abuot and the variable dynamic, whose type had widened to plain string, were errors. The template literal `/posts/${id}?tab=comments` passes, but the query content (the value of tab, or whether it is required) isn't checked. Also, because pathpida's path is of type string, router.push(url.path) produced the same error with typedRoutes enabled. That is why the wrapper above uses as Route.

FeaturepathpidatypedRoutes (built into Next.js)
Setupnpm package + generation scriptOne line in next.config.ts
Checks that the path existsYes (as properties of pagesPath)Yes (checks string literals directly)
Query types (required keys, allowed values)Yes (Query/OptionalQuery)No
push/replace/prefetch in next/navigationVia a wrapperYes
Pages Router next/routerYes (you can pass { pathname, query })No (<Link href> only)
Static file paths in public/Yes (staticPath with --enableStatic)No
How it readspagesPath.posts._id(1).$url(/engineer/455/...)Write "/posts/1" as usual

pathpida or typedRoutes: which should you use?

  • You only need to prevent broken links: typedRoutes is enough. No extra dependency or generation script, and you keep writing plain strings.
  • You want types for required query parameters and their values: use pathpida. The more screens pass search conditions, tabs or page numbers through the query, the more it pays off.
  • You still use the Pages Router's next/router: typedRoutes doesn't type router.push, so pathpida (plus the wrapper below) is useful.
  • Both: you can combine them. In that case you need to cast pathpida's path with as Route (as in the wrapper above).

If you pair a Next.js front end with a headless CMS, see "How to deploy Strapi to Render". For previewing files on the React side, see "Display PDF, images and HTML in React".

Legacy: the Pages Router implementation (Author's notes from November 2023)

From here on is the Pages Router implementation from the first version (November 2023, Next.js 14.0.1, pathpida 0.22). Part of the code wasn't displayed in the original post, so it was restored from the repository. When we upgraded only the dependencies to Next.js 16.5.0, React 19.3.1 and pathpida 0.28.0 and built it, the hook and page code passed type checking and the build without changes (in the Pages Router, the return value of $url() doesn't include path).

Create a new project with create-next-app.

# npx create-next-app
✔ What is your project named? … next-app
✔ Would you like to use TypeScript? … No / Yes  # chose Yes
✔ Would you like to use ESLint? … No / Yes.     # chose Yes
✔ Would you like to use Tailwind CSS? … No / Yes # chose Yes (either is fine)
✔ Would you like to use `src/` directory? … No / Yes  # chose Yes
✔ Would you like to use App Router? (recommended) … No / Yes  # chose No this time
✔ Would you like to customize the default import alias (@/*)? … No / Yes  # chose No this time
Creating a new Next.js app in XXXXX (your dir)
# cd next-app
# npm install --save-dev pathpida

Change the scripts in package.json so that pathpida generation runs when the server starts.

"scripts": {
  "dev": "pathpida && next dev",
  "build": "pathpida && next build",
  "start": "next start",
  "lint": "next lint"
}

Create the useRouter wrapper, useRouterWrapper, in src/hooks/useQueryWrapper.tsx.

useRouterWrapper takes two types as generics to make it type-safe.
The first type represents the object under router.query; the idea is to pass pathpida's type.
The second type is the type of the query when calling router.push.

import { useMemo } from "react";

import { ParsedUrlQuery } from "querystring";
import { Url } from "url";

import { useRouter } from "next/router";

// FuncUrlObject|UrlObject -> UrlReturnObject['query']
type GetUrlReturnObject<UrlObjectUnion extends FuncUrlObject | UrlObject> =
  UrlObjectUnion extends FuncUrlObject
    ? ReturnType<ReturnType<UrlObjectUnion>["$url"]>["query"]
    : UrlObjectUnion extends UrlObject
    ? ReturnType<UrlObjectUnion["$url"]>["query"]
    : never;

type UrlReturnObject = {
  pathname: string;
  query?: { [key: string]: string | string[] | number | undefined | any };
  hash: string | undefined;
};

type FuncUrlObject = (id: string | number) => {
  $url: (
    url?:
      | {
          hash?: string | undefined;
        }
      | undefined
  ) => UrlReturnObject;
};
type UrlObject = {
  $url: (
    url?:
      | {
          hash?: string | undefined;
        }
      | undefined
  ) => UrlReturnObject;
};

export const useRouterWrapper = <
  UrlObjectUnion extends FuncUrlObject | UrlObject,
  PushQueryParam = string | string[]
>() => {
  const router = useRouter();

  type QueryParam = GetUrlReturnObject<UrlObjectUnion>;

  // Winding ParsedUrlQuery->ParsedUrlQuery
  type AssertIsQueryParam = (
    value: ParsedUrlQuery | QueryParam
  ) => asserts value is QueryParam;
  const assertIsQueryParam: AssertIsQueryParam = (value) => {
    if (typeof value !== "object") {
      throw Error("router.query is not object");
    }
  };
  assertIsQueryParam(router.query);

  const query: QueryParam = router.query;

  const push = useMemo(
    () =>
      function (url: UrlReturnObject | (Url & { query?: PushQueryParam })) {
        router.push(url);
      },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );

  return { ...router, query, push };
};

Next, add a page that receives query parameters.
Create a [id].tsx file directly under the pages folder and implement it as follows.

import { useRouterWrapper } from "@/hooks/useQueryWrapper";
import { pagesPath } from "@/lib/$path";
import Link from "next/link";

export type OptionalQuery = { hoge: string | number };

function IdPage() {
  const pagePath = pagesPath._id("id");
  const router = useRouterWrapper<typeof pagePath>();
  const hoge = router.query.hoge;

  return (
    <>
      <div>
        <div>ID page</div>
        <div>id: {router.query.id}</div>
        <div>hoge: {hoge}</div>
      </div>
      <Link href={pagesPath.$url()} passHref>
        Back
      </Link>
    </>
  );
}

export default IdPage;

You can see that the type of the $url() implemented by pathpida is passed as the first type of useRouterWrapper.
This lets VS Code suggest hoge after router.query.

VS Code autocompleting hoge on router.query (UI labels translated to English)

Finally, edit the home page, pages/index.tsx.
Here, router.push is used where a Link would normally do.

import { useRouterWrapper } from "@/hooks/useQueryWrapper";
import { pagesPath } from "@/lib/$path";
import { type OptionalQuery } from "@/pages/[id]";

export default function Home() {
  const pagePath = pagesPath;

  const router = useRouterWrapper<typeof pagePath, OptionalQuery>();

  const onClickLink = () => {
    router.push(
      pagePath._id(1).$url({
        query: {
          hoge: "hogehoge",
        },
      })
    );
  };

  return (
    <div>
      <div>main</div>
      <button onClick={onClickLink}>click link</button>
    </div>
  );
}

Passing the query parameter type of the destination page as the second type of useRouterWrapper makes the argument of push type-safe.
As shown below, VS Code shows a warning if you forget hoge.

VS Code warning when hoge is not passed (UI labels translated to English)

Finally, check that it works.

# npm run dev

The index.tsx page with the click link button

Clicking "click link" on the index.tsx page navigates to the id page.

The id page after navigation (UI labels translated to English)

Final notes

One problem left in the first version's implementation was the handling of booleans and similar types.
If you pass true as a query parameter, the code treats it as a boolean, but at runtime you get the string "true".
Please treat this implementation as a reference only.

(Added December 2026) In the App Router version, the values on the reading side are typed as string | undefined, so this mismatch is now reflected in the types too. The current rule of thumb: use pathpida if you want to manage query types, and Next.js's built-in typedRoutes if checking that paths exist is enough.

References

Title and URL copied