DEV Community

Cover image for Type-Safe Route Paths in Next.js with next-typed-paths
Hugo Burton
Hugo Burton

Posted on

Type-Safe Route Paths in Next.js with next-typed-paths

Have you ever shipped a Next.js app only to find out you had a typo in a route path? Or maybe you refactored a folder and missed updating a hardcoded string somewhere? I’ve been there too. That’s why I built next-typed-paths — a tool to generate (in realtime) type-safe route paths for your Next.js project.

The Problem: Route Strings Are Fragile

Next.js file-based routing is awesome, but route paths are just strings. This can lead to:

  • Typos that only show up at runtime
  • Painful refactors when moving or renaming routes
  • No autocomplete or type checking for your app’s navigation

Real-World Example

Imagine you have a route like /api/users/[userId]. In your code, you might write:

apiClient.get(`/api/users/${userId}`).then((response) => response.data);
Enter fullscreen mode Exit fullscreen mode

But what if you accidentally type:

apiClient.get(`/api/user/${userId}`).then((response) => response.data);
// Oops missing an s
Enter fullscreen mode Exit fullscreen mode

Or you rename a folder from users to user and forget to update every string in your codebase. These mistakes are easy to make and can result in 404 errors that are only caught at runtime—sometimes by your users!

What About Next.js Static Typed Links?

Next.js recently made stable a feature called statically typed links, which is a great step forward. However, it only works for the next/link component and a few other built-in helpers. It doesn’t help with:

  • API calls (e.g., apiClient.get('/api/posts/123'))
  • Programmatic navigation (e.g., router.push)
  • Any custom logic that builds URLs

That’s where next-typed-paths comes in.

Why next-typed-paths?

next-typed-paths generates in realtime a fully typed schematic of your entire backend (and even client side routes), so you get:

  • Autocomplete for route paths
  • Compile-time errors for typos
  • Refactor-safe navigation

Installation

npm install next-typed-paths
# or
yarn add next-typed-paths
Enter fullscreen mode Exit fullscreen mode

For more details, see the README.

How It Works

  1. Point next-typed-paths at your routes directory.
  2. It scans your file structure and generates a TypeScript file with all your routes as typed helpers.
  3. Import and use these helpers in your app for type-safe navigation.

Example

Suppose you have this structure:

app/api
├── users
│   ├── route.ts
│   └── [userId]
│       └── route.ts
└── posts
    ├── route.ts
    └── [postId]
        ├── route.ts
        └── comments
            └── route.ts
Enter fullscreen mode Exit fullscreen mode

Run the generator:

npx next-typed-paths
Enter fullscreen mode Exit fullscreen mode

It generates schema to a file of your choosing (say @/generated/routes). Now, in your code:

import { API_ROUTES } from '@/generated/routes';

const postEndpoint = API_ROUTES.api.posts.postId('123'); // "/api/posts/123"
const postResponse = apiClient
                       .get<Post>(postEndpoint)
                       .then((response) => response.data);
Enter fullscreen mode Exit fullscreen mode

If you mistype a route or forget a parameter, TypeScript will catch it!

Advanced Features

  • Supports dynamic routes ([param])
    • Supports customised key value map to narrow typing for slugs. Example in e2e test: see here and here
  • Works with nested folders
  • Customisable output location
  • Watch mode for realtime updates to your schema when you edit your /src/app folder.

Why Use This Over Alternatives?

  • Very minimum runtime overhead. Of course the strings are constructed when being used, but at least with type safety at compile time
  • Works with any Next.js project structure
  • Can be used with API routes as well as client side routes
  • Fully type-safe and autocompletes everywhere

Try It Out!

  1. Install and run the generator.
  2. Import the generated routes in your app.
  3. Enjoy safer, faster navigation and refactoring!

Feedback & Contributions

I’d love to hear your feedback or ideas for improvement. PRs and issues are welcome!

GitHub Repo: https://github.com/hugs7/next-typed-paths
NPM Package: https://npmjs.com/package/next-typed-paths

Top comments (0)