Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/joulev/nextjs-route-types
Automatic type generation for Next.js app router dynamic route params
https://github.com/joulev/nextjs-route-types
codegen nextjs types
Last synced: 3 months ago
JSON representation
Automatic type generation for Next.js app router dynamic route params
- Host: GitHub
- URL: https://github.com/joulev/nextjs-route-types
- Owner: joulev
- License: mit
- Created: 2023-09-24T08:53:16.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-06-12T03:42:06.000Z (7 months ago)
- Last Synced: 2024-09-27T02:00:04.922Z (3 months ago)
- Topics: codegen, nextjs, types
- Language: TypeScript
- Homepage:
- Size: 569 KB
- Stars: 17
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: license.md
Awesome Lists containing this project
README
# nextjs-route-types
Automatic type generation for Next.js app router routes, ~~copied from~~ highly inspired by [SvelteKit](https://kit.svelte.dev).
## Installation
1. Install the package from NPM:
```sh
npm install nextjs-route-types # npm
yarn add nextjs-route-types # yarn
pnpm add nextjs-route-types # pnpm
bun add nextjs-route-types # bun
```2. Use the Next.js plugin in your Next.js config file
```js
const { withNextJSRouteTypes } = require("nextjs-route-types");/** @type {import("next").NextConfig} */
const nextConfig = {
// your Next.js configurations
};module.exports = withNextJSRouteTypes(nextConfig);
```3. Configure `tsconfig.json`: Add `"rootDirs": [".", ".next-types"]` to your `compilerOptions`. This step is necessary, we need this for TypeScript to know where to look when we import from `./$types`.
4. If you use Git you might want to add `.next-types` to `.gitignore`.
## Usage
In any files inside the `app` directory (or `src/app` if you use it), you can import certain types from `"./$types"`:
```tsx
// app/[dynamic]/[nested]/page.tsx
import type { PageProps } from "./$types";export default function Page({ params }: PageProps) {
console.log(params.dynamic); // string
returnHello world;
}
``````tsx
// app/[dynamic]/[...another]/route.ts
import type { RouteHandler } from "./$types";export const GET: RouteHandler = (request, { params }) => {
console.log(params.another); // string[];
return new Response();
};
````./$types` exports the following types: `SearchParams`, `Params`, `DefaultProps`, `ErrorProps`, `LayoutProps`, `LoadingProps`, `NotFoundProps`, `PageProps`, `TemplateProps`, `RouteHandlerContext` and `RouteHandler`.
> **Note**
> Editor IntelliSense might not work and you likely have to type that import statement manually. This is a known issue that I don't know how to fix – PRs welcome.## Credits
[SvelteKit](https://kit.svelte.dev) for the idea of using `rootDirs` for this.
[`nextjs-routes`](https://github.com/tatethurston/nextjs-routes) on which the Next.js plugin part of this code is based.