next-auto-routes
v0.0.1
Published
Generate auto-routes.ts file for Next.js App Router based on file system routing convention
Maintainers
Readme
next-auto-routes
A Next.js package that automatically generates TypeScript route definitions based on your App Router file system structure.
Features
- 🔍 Automatic Route Discovery: Scans your
appdirectory and discovers all routes based on Next.js App Router conventions - 📝 TypeScript Support: Generates fully typed route definitions with proper TypeScript interfaces
- 🎯 Dynamic Routes: Supports dynamic routes
[id], catch-all routes[...slug], and optional catch-all routes[[...slug]] - 🏗️ Hierarchical Structure: Creates a nested route structure that mirrors your file system
- ⚡ CLI Tool: Simple command-line interface for easy integration
- 🔧 Configurable: Options to include layouts, loading, error, and not-found files
Installation
npm install next-auto-routesUsage
CLI Usage
Run the command from your Next.js project root:
npx next-auto-routesThis will generate ./lib/utils/auto-routes.ts by default.
CLI Options
npx next-auto-routes [options]
Options:
-a, --app-dir <path> Path to the app directory (default: ./app)
-o, --output <path> Output path for the generated routes file (default: ./lib/utils/auto-routes.ts)
--include-layouts Include layout files in the generated routes
--include-loading Include loading files in the generated routes
--include-error Include error files in the generated routes
--include-not-found Include not-found files in the generated routes
-h, --help Display help for command
-V, --version Display version for commandProgrammatic Usage
import { generateRoutesFromAppDir } from 'next-auto-routes';
// Generate routes with default settings
await generateRoutesFromAppDir();
// Generate routes with custom options
await generateRoutesFromAppDir('./app', './src/routes.ts', {
includeLayouts: true,
includeLoading: true,
includeError: true,
includeNotFound: true
});Generated Output
The package generates a TypeScript file with the following structure:
// Auto-generated routes file
// Generated by next-auto-routes
// Do not edit manually
export interface HomeRoute extends RouteInfo {}
export interface BlogRoute extends RouteInfo {
post: RouteInfo;
}
export const HOME_ROUTE = '/';
export const BLOG_ROUTE = '/blog';
export const BLOG_POST_ROUTE = (slug: string) => `/blog/${slug}`;
export interface RouteInfo {
name: string;
path: string;
params: string[];
children?: RouteInfo[];
}
export const routes = {
home: {
name: 'home',
path: '/',
params: []
},
blog: {
name: 'blog',
path: '/blog',
params: [],
children: {
post: {
name: 'post',
path: '/blog/[slug]',
params: ['slug']
}
}
}
} as const;
export type AppRoutes = typeof routes;
export type RouteNames = keyof AppRoutes;File System Structure Examples
Basic Routes
app/
├── page.tsx → /
├── about/
│ └── page.tsx → /about
├── blog/
│ ├── page.tsx → /blog
│ └── [slug]/
│ └── page.tsx → /blog/[slug]
└── contact/
└── page.tsx → /contactDynamic Routes
app/
├── users/
│ ├── page.tsx → /users
│ └── [id]/
│ ├── page.tsx → /users/[id]
│ └── posts/
│ └── page.tsx → /users/[id]/posts
├── products/
│ ├── page.tsx → /products
│ └── [...slug]/
│ └── page.tsx → /products/[...slug]
└── docs/
└── [[...slug]]/
└── page.tsx → /docs/[[...slug]]Using Generated Routes
Type-Safe Navigation
import { routes, BLOG_POST_ROUTE } from '@/utils/auto-routes';
// Type-safe route access
const blogRoute = routes.blog;
const postRoute = routes.blog.post;
// Dynamic route generation
const postUrl = BLOG_POST_ROUTE('my-post-slug'); // '/blog/my-post-slug'Next.js Link Component
import Link from 'next/link';
import { BLOG_POST_ROUTE } from '@/utils/auto-routes';
export default function BlogList() {
return (
<div>
<Link href={BLOG_POST_ROUTE('first-post')}>
First Post
</Link>
</div>
);
}Programmatic Navigation
import { useRouter } from 'next/navigation';
import { BLOG_POST_ROUTE } from '@/utils/auto-routes';
export default function BlogCard({ slug }: { slug: string }) {
const router = useRouter();
const handleClick = () => {
router.push(BLOG_POST_ROUTE(slug));
};
return (
<button onClick={handleClick}>
Read Post
</button>
);
}Configuration
TypeScript Configuration
Make sure your tsconfig.json includes the generated routes file:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
}Next.js Configuration
Add the generated routes to your Next.js configuration if needed:
// next.config.js
module.exports = {
experimental: {
typedRoutes: true
}
}Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
