safe-router
v0.1.1
Published
⚡️ Type-safe routing for Next.js
Downloads
133
Maintainers
Readme
safe-router
⚡️ Automagic type-safe route generation for Next.js.
Features
- ✅ 100% type-safe
- ✅ Runs as a language service plugin
- ✅ Watches for changes in the app directory
- ✅ Supports dynamic and catch-all routes
Goals
- 🚧 Built-in support for query parameters
- 🚧 Support for pages router
- 🚧 Support for other frameworks like Remix
Requirements
- Next.js >=12
- TypeScript >=5.0
Setup
Install the package from the npm registry:
npm install safe-router
Now, add the following to your tsconfig.json
:
{
"compilerOptions": {
// ...
"plugins": [
// ...
{
"name": "safe-router",
"appFolder": "app" // (optional)
"outputFile": "routes.generated.ts" // (optional)
}
]
}
}
Usage
Given the following directory structure:
app/
├── api
│ ├── [[...params]]
│ │ └── route.ts
├── products
│ ├── [id]
│ │ ├── details
│ │ │ └── page.tsx
│ │ └── page.tsx
│ └── page.tsx
├── settings
│ └── page.tsx
└── page.tsx
Use the exported routes
object to access your routes:
import { routes } from './routes.generated'
routes.get() // /
routes.api.get() // /api
routes.api.params('hello', 'world') // /api/hello/world
routes.products.get() // /products
routes.products.id('123').get() // /products/123
routes.products.id('123').details.get() // /products/123/details
routes.settings.get() // /settings