# next-typed-connect

> A library for creating type-safe APIs in next.js.

Latest version **0.0.34** (published 2023-04-13) · 0 weekly downloads

## Install

```sh
npm install next-typed-connect
pnpm add next-typed-connect
yarn add next-typed-connect
bun add next-typed-connect
```

Provides the command `next-typed-connect`.

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.34 |
| Published | 2023-04-13 |
| First published | 2023-04-10 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 10 |
| Unpacked size | 342.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | steelydylan |

## Links

- npm: https://www.npmjs.com/package/next-typed-connect
- npm.io page: https://npm.io/package/next-typed-connect

## Dependencies (10)

- [qs](https://npm.io/package/qs.md) ^6.11.1
- [rimraf](https://npm.io/package/rimraf.md) ^5.0.0
- [ts-node](https://npm.io/package/ts-node.md) ^10.9.1
- [chokidar](https://npm.io/package/chokidar.md) ^3.5.3
- [fs-extra](https://npm.io/package/fs-extra.md) ^11.1.1
- [@types/qs](https://npm.io/package/@types/qs.md) ^6.9.7
- [commander](https://npm.io/package/commander.md) ^10.0.0
- [typescript](https://npm.io/package/typescript.md) ^5.0.4
- [@types/fs-extra](https://npm.io/package/@types/fs-extra.md) ^11.0.1
- [node-mocks-http](https://npm.io/package/node-mocks-http.md) ^1.12.2

## Recent versions

- 0.0.34 (latest) — 2023-04-13
- 0.0.33 — 2023-04-13
- 0.0.32 — 2023-04-13
- 0.0.31 — 2023-04-13
- 0.0.30 — 2023-04-12
- 0.0.29 — 2023-04-12
- 0.0.28 — 2023-04-12
- 0.0.27 — 2023-04-12
- 0.0.26 — 2023-04-12
- 0.0.25 — 2023-04-12
- 0.0.24 — 2023-04-11
- 0.0.23 — 2023-04-11
- 0.0.22 — 2023-04-11
- 0.0.21 — 2023-04-11
- 0.0.20 — 2023-04-11
- … 19 more at https://npm.io/package/next-typed-connect/versions

## README

# next-typed-connect

A library for creating type-safe APIs in next.js.

## Motivation

I wanted to create type-safe APIs in Next.js using zod and also wanted to generate type definition files for client-side use so that I could use intuitive API calls.
But I couldn't find a library that met my needs, so I created this library.

## Features

- Type-safe API routing
- Type-safe API call
- error handling
- Type definition file generation
- Middleware support


## Demo

https://stackblitz.com/edit/next-typescript-32qrbx?embed=1&file=pages/index.tsx&file=pages/api/sample/[id].ts&hideNavigation=1&view=editor

## Usage

### Installation


```bash
## npm
npm install next-typed-connect

## yarn
yarn add next-typed-connect
```

### Server-side

1. Use zod to define the types for body, query, and res.
2. Create routing handling with createRouter.
3. Assign types to the created routing handling with validate.
4. Export the types as GetHandler and PostHandler.

```ts
// pages/api/sample.ts
import { ApiHandler, createRouter, validate } from "next-typed-connect";
import { z } from "zod";

/* Schema definition using zod */
const postValidation = {
  body: z.object({
    foo: z.string(),
  }),
  query: z.object({
    bar: z.string().optional(),
  }),
  res: z.object({
    message: z.string(),
  }),
}

const getValidation = {
  query: z.object({
    bar: z.string().optional(),
  }),
  res: z.object({
    message: z.string(),
  }),
}    

/* Routing */
const router = createRouter()

router
  .use((req, res, next) => {
    console.log("middleware");
    return next()
  })
  .post(
    validate(postValidation),
    (req, res) => {
      req.body.foo;
      req.query.bar;
      res.status(200).json({ message: "ok" });
    })
  .get(
    validate(getValidation),
    (req, res) => {
      req.query.bar;
      res.status(200).json({ message: "ok" });
    })

/* Type export */
// the export type name should be as follows
// so that the type definition file can be generated correctly via the command.
export type PostHandler = ApiHandler<typeof postValidation>
export type GetHandler = ApiHandler<typeof getValidation>

/* Routing handling export */
export default router.run()
```

### Error handling


#### throw error

```ts
// pages/api/sample.ts
router
  .post(
    validate(postValidation),
    (req, res) => {
      const session = getSession(req)
      if (!session) {
        throw createError(401, "Unauthorized")
      }
      res.status(200).json({ message: "ok" });
    })
```

#### custom error handling

```ts
// pages/api/sample.ts

router
  .onError((err, req, res) => {
    // custom error handling
    res.status(err.statusCode).json({ message: err.message });
  })
```

### dynamic routing

#### Server-side

```ts
// pages/api/[id].ts

const getValidation = {
  // 👇 for server side validation
  // 👇 also necessary for client side url construction
  query: z.object({
    id: z.string().optional(),
  }),
}

router
  .get(
    validate(getValidation),
    (req, res) => {
      req.query.id;
      res.status(200).json({ message: "ok" });
    })
```

#### Client-side

```ts
// client.ts
import { client } from "next-typed-connect";

client.get("/api/[id]", {
  query: {
    id: "1",
  },
})

// url will be /api/1
```

### Type generation


```bash
## npm
npx next-typed-connect

## yarn
yarn next-typed-connect
```

Adding a script to your package.json is convenient.

```json
{
  "scripts": {
    "apigen": "next-typed-connect"
  }
}
```

```bash
npm run apigen
```

### Client-side

```ts
import { client } from "next-typed-connect";

// Type-safe API call
const { data, error } = await client.post("/api/sample", {
  query: {
    bar: "baz",
  },
  body: {
    foo: "bar",
  },
})
```

## Command options

The default pages directory is `pages`, so if you want to change it, you can use the `--pagesDir` option.

```bash
next-typed-connect --pagesDir=src/pages
```

| Option | Description | Default value |
| --- | --- | --- |
| --pagesDir | Pages directory | pages |
| --baseDir | Project directory | . |
| --distDir | Type definition file output destination	 | node_modules/.next-typed-connect |
| --moduleNameSpace | Type definition file module name | .next-typed-connect |

## Tips

If you want to add session property to Request type, you can use the following code.

```ts
// global.d.ts
import { IncomingMessage } from "http";

declare module 'next' {
  export interface NextApiRequest extends IncomingMessage {
    session: Session
  }
}
```

---
_Source: https://npm.io/package/next-typed-connect · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
