1.1.0 • Published 5 months ago

nextjs-route-types v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

nextjs-route-types

Automatic type generation for Next.js app router routes, copied from highly inspired by SvelteKit.

Installation

  1. Install the package from NPM:

    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

    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":

// app/[dynamic]/[nested]/page.tsx
import type { PageProps } from "./$types";

export default function Page({ params }: PageProps) {
  console.log(params.dynamic); // string
  return <div>Hello world</div>;
}
// 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 for the idea of using rootDirs for this.

nextjs-routes on which the Next.js plugin part of this code is based.

1.1.0

5 months ago

1.0.2

7 months ago

1.0.1

8 months ago

1.0.0

8 months ago

0.0.3

8 months ago

0.0.2

8 months ago

0.0.1

8 months ago