# Taser.js API Router Quick Reference > Taser.js is a type-safe, file-based REST API router for TypeScript. Packages: `@taserjs/router`, `@taserjs/cli`, `@taserjs/plugin`, `@taserjs/client`. Runs on Vite standalone, Nitro, Next.js App Router, TanStack Start, and host pass-through (Express, Fastify, Hono). ## Canonical Architecture - App definition: `export default defineTaser({ ... })` from `@taserjs/router` (uninstantiated `TaserDefinition`). - Generated entry: `src/.taserjs/routes.gen.ts` exports runnable `app`, ambient types, and `AppManifest`. - Paths: configure `serverDir` / `routesDir` / `outputDir` in `taserjs.config.ts` via `@taserjs/cli`. - Mount URL prefix with `defineTaser().basePath("/api")` — never on plugin options. - Next plugin options are only `cwd?` and `config?` (`createTaser` from `@taserjs/plugin/next`). ## Core File Naming Conventions - Root Route: `src/routes/index.get.ts` -> GET / - Dynamic Param: `src/routes/users/$id.get.ts` -> GET /users/:id - Nested Flat Route: `src/routes/users.$id.posts.get.ts` -> GET /users/:id/posts - Catch-All Splat: `src/routes/files.$.get.ts` -> GET /files/* (`req.params._splat`) - Pathless Layout: `src/routes/_auth.ts` -> Scoped middleware for pathless group - Directory Layout: `src/routes/api/$.ts` -> Scoped middleware for /api/* ## Route Handler Pattern ```ts import { json, notFound } from "@taserjs/router/reply"; import { t } from "@taserjs/router"; import { z } from "zod"; const GET = t .get("/users/:id") .params(z.object({ id: z.string().uuid() })) .query(z.object({ limit: z.coerce.number().default(10) })) .returns({ 200: z.object({ id: z.string(), name: z.string() }), 404: z.object({ message: z.string() }), }); export default GET.handler(async ({ req, ctx }) => { const user = await ctx.db.findUser(req.params.id); if (!user) { return notFound({ message: "User not found" }); } return json(user); }); ``` ## Middleware & Layout Pattern Handler/middleware args are facet-split: `{ req, ctx, state, ...services }`. ```ts import { unauthorized } from "@taserjs/router/reply"; import { t } from "@taserjs/router"; export default t.layout("/dashboard").use(async ({ req }, next) => { const authHeader = req.headers.get("authorization"); if (!authHeader) { return unauthorized({ message: "Missing authorization" }); } return next({ user: { id: "user_123", role: "admin" } }); }); ``` ## Cookies Mount `cookie()` from `@taserjs/router/middleware/cookie` on a layout, then use `{ cookies }` (Cookie Jar Instance). ## Streams From `@taserjs/router/stream`: `pipe`, `buffer`, `blob`, `sse`. There is no `file()` helper. ## Typed Client ```ts import { createClient } from "@taserjs/client"; import type { AppManifest } from "./.taserjs/routes.gen.js"; const api = createClient({ baseUrl: "/api" }); await api.users._id.$get({ param: { id: "..." } }); ``` ## Reply Helpers From `@taserjs/router/reply`: - `json`, `text`, `html`, `noContent`, `redirect` - `badRequest`, `unauthorized`, `forbidden`, `notFound`, `unprocessableEntity`, `internalServerError`, etc. ## Generate - Dev/build: `@taserjs/plugin` regenerates `routes.gen.ts` - Standalone: `taser generate` / `npx @taserjs/cli generate` --- # Documentation Index # Documentation - [Introduction](/docs): High-performance, file-based REST API router for TypeScript. Zero runtime drift, cascading middleware context, and automatic client generation. - Getting Started - [Quickstart](/docs/getting-started): Create and run a new Taser.js project in under a minute with create-taserjs. Choose your favorite server adapter, schema validator, ORM, and logger. - [Manual Installation](/docs/getting-started/manual-installation): Step-by-step guide to installing and configuring Taser.js manually with Vite, Nitro deployment presets, Next.js, and host pass-through dispatching. - [Core Concepts](/docs/getting-started/core-concepts): Master Taser.js architecture: four core pillars, request lifecycle flow, context injection, cascading middleware, and compiler-enforced return contracts. - [Migration Guide](/docs/getting-started/migration): Incrementally migrate existing Express or Fastify APIs to Taser.js with zero downtime using the host pass-through architecture. - **Core Guides** - Routing System - [File Conventions](/docs/routing/file-conventions): Master TanStack Router-style file conventions for REST APIs. Learn flat routes, nested folders, path params ($id), catch-alls ($), and layouts. - [Defining Routes](/docs/routing/defining-routes): Learn how to define type-safe route endpoints using Taser.js's fluent route builder. Chain query, params, body schemas, middlewares, and response contracts. - [Layouts and Middleware](/docs/routing/layouts-and-middleware): Compose shared logic, authentication guards, and cascading typed state with layout files. Understand middleware execution ordering and state propagation. - [Context and State](/docs/routing/context-and-state): Learn how to manage application singletons and request-scoped state with createContext. Understand boot context, request context, and native runtime interop. - Validation - [Standard Schema Validation](/docs/validation/standard-schema): Validate query parameters, path params, request bodies, and headers using Zod, ArkType, Valibot, or any Standard Schema library. - [Middleware Validation](/docs/validation/middleware-validation): Validate incoming headers, auth tokens, and session context at the layout level before requests reach downstream REST API route handlers. - [Handling Validation Errors](/docs/validation/handling-errors): Understand built-in ValidationError (422) handling and customize envelopes with middleware try/catch — they bypass defineTaser().onError(). - Responses & Errors - [Reply Helpers](/docs/responses/reply-helpers): Send clean, status-discriminated HTTP responses using tree-shakeable reply helpers: json(), ok(), notFound(), and redirect(). - [Cookie Management](/docs/responses/cookies): Mount the first-party cookie() middleware to get a Cookie Jar Instance in your handlers. Read, set, sign, and delete HTTP cookies. - [Response Contracts](/docs/responses/response-contracts): Enforce compile-time return shape safety and runtime response validation with .returns(). Eliminate response drift between backend and frontend. - [Streaming and Web Payloads](/docs/responses/streaming-and-files): Stream Web ReadableStreams, binary buffers, Blobs, and Server-Sent Events with edge-compatible helpers from @taserjs/router/stream. - [Global Error Handling](/docs/responses/error-handling): Catch unhandled runtime crashes with .onError() and customize 404s with .notFound(). Protocol errors (422/415) and response contracts bypass onError. - Built-in Middlewares - [CORS Middleware](/docs/middleware/cors): Configure Cross-Origin Resource Sharing (CORS) using @taserjs/router/cors with static origins, dynamic domain resolvers, and preflight support. - [JWT and JWKS Authentication](/docs/middleware/jwt-and-jwk): Verify JSON Web Tokens (JWT) and remote JWKS key sets (Auth0, Clerk, Supabase) with built-in typed authentication middleware for Taser.js APIs. - [Security and Utility Middlewares](/docs/middleware/security-and-utilities): Discover built-in middlewares for security headers, CSRF defense, body size limits, ETags, Server-Timing, and response compression. - **Architecture & Integration** - Framework Adapters - [Standalone API](/docs/frameworks/standalone): Build standalone, zero-host HTTP APIs with pure Taser.js, Vite, and Nitro. Maximum throughput, zero boilerplate, and web-standard Request/Response execution. - [Native Fetch Frameworks](/docs/frameworks/fetch-native): Run Taser.js alongside any Web Standard or Fetch-native host framework (Hono, Elysia, HatTip, or native Web Fetch handlers) using host pass-through dispatching. - [Express Integration](/docs/frameworks/express): Add Taser.js file-based routing to an Express application. Coexist with legacy controllers and middleware using the host pass-through architecture. - [Fastify Integration](/docs/frameworks/fastify): Pair Taser.js file routing with Fastify. Coexist with Fastify plugins, hooks, and native route handlers using host pass-through architecture. - Full-Stack Frameworks - [TanStack Start](/docs/fullstack/tanstack-start): Build fullstack React applications with TanStack Start and Taser.js. Type-safe data fetching in TanStack Router loaders, React Query, and multi-runtime Nitro deployment. - [Next.js App Router](/docs/fullstack/nextjs): Build fullstack Next.js 15+ App Router applications with a dedicated Taser.js REST API subsystem. Type-safe data fetching in React Server Components, Server Actions, and Client Components. - Plugins & Compilers - [Vite Plugin](/docs/plugins/vite): Integrate Taser.js with Vite using @taserjs/plugin/vite. Manifest generation, HMR, and standalone or Nitro-backed builds. - [Next.js Plugin](/docs/plugins/next): Configure @taserjs/plugin/next for Next.js 15+ App Router: createTaser with cwd/config, and routes.gen.ts generation. - [Nitro Module](/docs/plugins/nitro): Deploy Taser.js with @taserjs/plugin/nitro — standalone or fullstack Nitro handlers across edge and serverless presets. - [Bundler Adapters](/docs/plugins/bundlers): Use Taser.js with Webpack, Rspack, Rollup, Rolldown, or Esbuild via @taserjs/plugin subpath exports. - [Deployment Presets](/docs/deployments): Deploy Taser.js APIs across Cloudflare Workers, Vercel, AWS Lambda, Node.js, Bun, Deno, and Netlify using multi-cloud Nitro server presets. - [Typed Client SDK](/docs/client): Connect to Taser.js backends with end-to-end type safety using @taserjs/client. Enjoy autocomplete for routes, query schemas, and return types. - **Ecosystem & Reference** - [CLI & Type Generation](/docs/cli): Generate src/.taserjs/routes.gen.ts, scaffold empty route files, and run standalone typechecks with @taserjs/cli. - API Reference - [@taserjs/router](/docs/api-reference/router): Complete API reference for @taserjs/router: createTaserApp, createContext, fluent RouteBuilder chaining, reply helpers, and core types. - [@taserjs/plugin](/docs/api-reference/plugin): API reference for @taserjs/plugin across Vite, Next.js, Nitro, and other bundlers. - [@taserjs/client](/docs/api-reference/client): Complete API reference for @taserjs/client: createClient options, fetch interop, formBody utilities, and end-to-end TypeScript types. - [@taserjs/cli](/docs/api-reference/cli): CLI reference for taser generate, taserjs.config.ts, and src/.taserjs/routes.gen.ts output.