Skip to main content
skill CX Codex

server-routes — Claude Code skill: what it does, how to install

This skill guides an agent through API endpoints in TanStack Router, including HTTP handlers and request parsing. Use it when routes need an HTTP contract.

MIT 205 installs ★ 15,341 updated 2026-10-25

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add TanStack/router --skill server-routes -a claude-code
Open on GitHub

What server-routes does

The skill teaches the agent to define API endpoints with the server option of createFileRoute. It covers GET, POST, PUT, and DELETE handlers, path parameters, request bodies, and responses with JSON, headers, or status codes. Route files live under src/routes and follow TanStack Router’s file conventions.

Its examples cover handler context such as request, params, context, pathname, and next. The agent can also set middleware for every method or attach it to one method through createHandlers. A single file may contain both a server route and a UI route. The skill requires start-core.

An SSR loader should not call its own endpoint through fetch; shared work belongs in a server-only service exposed at the required boundaries. That rule affects how the application code should be split.

What it helps with

  • define an API route beside an application route
  • parse JSON from a POST request
  • read a dynamic path parameter
  • return JSON with a chosen status code
  • attach middleware to one HTTP method

Example prompts for the agent

  • Create src/routes/api/users.ts with GET and POST handlers.
  • Add validation middleware to POST in src/routes/api/posts.ts, while keeping GET public.
  • Show how to read params.id and return a 404 response when the user is missing.

How to install server-routes

1Skills CLI (Vercel)

npx skills add TanStack/router --skill server-routes -a claude-code

2Manually: put the files in place

~/.claude/skills/server-routes/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/server-routes/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about server-routes

How do I install server-routes in Claude Code?

Run npx skills add TanStack/router --skill server-routes -a claude-code. Then check ~/.claude/skills/server-routes/SKILL.md.

What does server-routes do?

It guides the agent in building API routes with createFileRoute, handling HTTP methods, reading request data, and returning responses. It also covers middleware and route file naming.

Does server-routes require another TanStack component?

The skill requires start-core. Server routes are intended for an HTTP contract, while app-only data should use a server function.

Source text

SKILL.md · MIT
---
name: server-routes
description: >-
  Server-side API endpoints using the server property on
  createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE),
  createHandlers for per-handler middleware, handler context
  (request, params, context), request body parsing, response
  helpers, file naming for API routes.
metadata:
  type: sub-skill
  library: tanstack-start
  library_version: '1.170.14'
requires:
  - start-core
sources:
  - TanStack/router:docs/start/framework/react/guide/server-routes.md
---

# Server Routes

Server routes are API endpoints defined alongside app routes in the `src/routes` directory. They use the `server` property on `createFileRoute` and handle raw HTTP requests.

Use server routes when callers need an HTTP contract. For data used only by the Start application, prefer a server function and call it directly from the loader. A route loader runs during SSR and client navigation, so `fetch('/api/...')` is not a portable loader pattern.

## Basic Server Route

```ts
// src/routes/api/hello.ts
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/api/hello')({
  server: {
    handlers: {
      GET: async ({ request }) => {
        return new Response('Hello, World!')
      },
    },
  },
})
```

## Combining Server Route and App Route

The same file can define both a server route and a UI route:

```tsx
// src/routes/hello.tsx
import { createFileRoute } from '@tanstack/react-router'
import { useState } from 'react'

export const Route = createFileRoute('/hello')({
  server: {
    handlers: {
      POST: async ({ request }) => {
        const body = await request.json()
        return Response.json({ message: `Hello, ${body.name}!` })
      },
    },
  },
  component: HelloComponent,
})

function HelloComponent() {
  const [reply, setReply] = useState('')
  return (
    <button
      onClick={() => {
        fetch('/hello', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name: 'Tanner' }),
        })
          .then((res) => res.json())
          .then((data) => setReply(data.message))
      }}
    >
      Say Hello {reply && `- ${reply}`}
    </button>
  )
}
```

The relative `fetch('/hello')` above is safe because it runs only in a browser click handler.

## Sharing Data with a Start Route

Do not make the SSR loader call its own server route. Put the business operation in a server-only service, then expose it through both boundaries when both are required:

```tsx
// src/server/issues.server.ts
export function listIssues() {
  return db.issues.findMany()
}

// src/routes/api/issues.ts
export const Route = createFileRoute('/api/issues')({
  server: {
    handlers: {
      GET: async () => Response.json(await listIssues()),
    },
  },
})

// src/routes/issues.tsx
const getIssues = createServerFn({ method: 'GET' }).handler(() => {
  return listIssues()
})

export const Route = createFileRoute('/issues')({
  loader: () => getIssues(),
})
```

This keeps SSR independent of URL resolution and keeps one source of business logic.

## File Route Conventions

Server routes follow TanStack Router file-based routing conventions:

| File                        | Route                         |
| --------------------------- | ----------------------------- |
| `routes/users.ts`           | `/users`                      |
| `routes/users/$id.ts`       | `/users/$id`                  |
| `routes/users/$id/posts.ts` | `/users/$id/posts`            |
| `routes/api/file/$.ts`      | `/api/file/$` (splat)         |
| `routes/my-script[.]js.ts`  | `/my-script.js` (escaped dot) |

## Unique Route Paths

Each route can only have a single handler file. These would conflict:

- `routes/users.ts`
- `routes/users.index.ts`
- `routes/users/index.ts`

## Handler Context

Each handler receives:

- `request` — the incoming [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object
- `params` — dynamic path parameters
- `context` — context from middleware
- `pathname` — the matched pathname
- `next` — call to fall through to SSR (returns a `Response`)

## Dynamic Path Params

```ts
// routes/users/$id.ts
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/users/$id')({
  server: {
    handlers: {
      GET: async ({ params }) => {
        return new Response(`User ID: ${params.id}`)
      },
    },
  },
})
```

## Splat/Wildcard Params

```ts
// routes/file/$.ts
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/file/$')({
  server: {
    handlers: {
      GET: async ({ params }) => {
        return new Response(`File: ${params._splat}`)
      },
    },
  },
})
```

## Request Body Handling

```ts
export const Route = createFileRoute('/api/users')({
  server: {
    handlers: {
      POST: async ({ request }) => {
        const body = await request.json()
        return Response.json({ created: body.name })
      },
    },
  },
})
```

Other body methods: `request.text()`, `request.formData()`.

## JSON Responses

```ts
// Using Response.json helper
handlers: {
  GET: async () => {
    return Response.json({ message: 'Hello!' })
  },
}
```

## Status Codes and Headers

```ts
handlers: {
  GET: async ({ params }) => {
    const user = await findUser(params.id)
    if (!user) {
      return new Response('Not found', { status: 404 })
    }
    return Response.json(user)
  },
}
```

```ts
handlers: {
  GET: async () => {
    return new Response('Hello', {
      headers: { 'Content-Type': 'text/plain' },
    })
  },
}
```

## Middleware on Server Routes

### All handlers

```tsx
export const Route = createFileRoute('/api/admin')({
  server: {
    middleware: [authMiddleware, loggerMiddleware],
    handlers: {
      GET: async ({ context }) => Response.json(context.user),
      POST: async ({ request, context }) => {
        /* ... */
      },
    },
  },
})
```

### Specific handlers with createHandlers

```tsx
export const Route = createFileRoute('/api/data')({
  server: {
    handlers: ({ createHandlers }) =>
      createHandlers({
        GET: async () => Response.json({ public: true }),
        POST: {
          middleware: [authMiddleware],
          handler: async ({ context }) => {
            return Response.json({ user: context.session.user })
          },
        },
      }),
  },
})
```

### Combined route-level and handler-specific

```tsx
export const Route = createFileRoute('/api/posts')({
  server: {
    middleware: [authMiddleware], // runs first for all
    handlers: ({ createHandlers }) =>
      createHandlers({
        GET: async () => Response.json([]),
        POST: {
          middleware: [validationMiddleware], // runs after auth, POST only
          handler: async ({ request }) => {
            const body = await request.json()
            return Response.json({ created: true })
          },
        },
      }),
  },
})
```

## Common Mistakes

### 1. CRITICAL: Protecting the page but not the server route

Every handler that reads or writes private data must authenticate and authorize the request through route middleware, handler middleware, or an in-handler check. A router `beforeLoad` redirect does not protect `/api/...`. Test the handler directly without cookies and assert that no private payload is returned.

### 2. MEDIUM: Duplicate route paths

```text
# WRONG — both resolve to /users, causes error
routes/users.ts
routes/users/index.ts

# CORRECT — pick one
routes/users.ts
```

### 3. MEDIUM: Forgetting to await request body methods

```ts
// WRONG — body is a Promise, not the actual data
const body = request.json()

// CORRECT — await the promise
const body = await request.json()
```

### 4. HIGH: Trusting TypeScript as response-schema validation

Validate request input and test the serialized `Response` output. A typed service can still be projected or serialized without a newly added field. For schema changes, assert `await response.json()` at the server-route boundary.

## Cross-References

- [start-core/middleware](../middleware/SKILL.md) — middleware for server routes
- [start-core/server-functions](../server-functions/SKILL.md) — alternative for RPC-style calls

© TanStack · MIT · TanStack/router

Similar skills

All skills for Backend and APIs →
vtex-io-http-routes vtex vtex-io-http-routes guides the design of HTTP endpoints in a VTEX IO backend service: route boundaries, middleware chains, request validation and response shape. CX Codex +1 1,200installs Cross-Chain Bridge Routes — 60+ Chains via LI.FI axel-belfort Cross-Chain Bridge Routes — 60+ Chains via LI.FI is an MCP server for Claude Code that compares token routes across 60+ chains and shows fees, timing, and security ratings before transfers. CX Codex +1 3,748installs expo-api-routes official Expo Team The expo-api-routes skill tells the agent how to write server-side API routes in Expo Router and ship them to EAS Hosting. Useful when keys and database calls must stay off the client. CX Codex GP ChatGPT +1 1installs async-api-routes tech-leads-club async-api-routes prevents sequential waterfall requests in API routes and Server Actions. It instructs the assistant to launch independent promises immediately rather than chaining awaits. CX Codex +1 ★ 7,191repo stars nextjs-dynamic-routes-params wsimmonds nextjs-dynamic-routes-params — a skill that steers the agent through App Router dynamic segments and the params prop in Next.js 15+. Useful when a page depends on an ID or slug from the URL. CX Codex +1 304installs tanstack-start-cursorrules-prompt-file PatrickJS tanstack-start-cursorrules-prompt-file — a Cursor rule for TanStack Start, a full-stack React framework with SSR, server functions and type safety. Triggers when you work on Start projects, TanStack Router routes or Vinxi config files. CX Codex +1 ★ 41,178repo stars

From the same set25

The whole set →
not-found-and-errors not-found-and-errors teaches coding agents to configure 404 boundaries and error components in TanStack Router. It covers throwing notFound() and handling loader failures. CX Codex +1 211installs deployment deployment deploys TanStack Start to Cloudflare Workers, Netlify, Vercel, Node.js, Bun, and Railway. Controls SSR per route, static prerendering, and SEO config. CX Codex +1 210installs path-params path-params — a skill for handling dynamic URL parameters in TanStack Router. Teaches agents to capture variable path segments, set up optional routes, and create patterns with prefixes and suffixes. CX Codex +1 208installs middleware Covers TanStack Start middleware: createMiddleware, context chaining via next(), sendContext for cross-boundary transfers, and global registration in src/start.ts. CX Codex +1 206installs ssr The ssr skill for Claude Code configures streaming or non-streaming server-side rendering in TanStack Router for projects integrating the router with an existing server. CX Codex +1 202installs auth-server-primitives auth-server-primitives is a Claude Code skill for server-side authentication in TanStack Start. It covers session handling, OAuth, password-reset defenses, and protection for server functions. CX Codex +1 201installs migrate-from-react-router migrate-from-react-router is a Claude Code skill with a step-by-step checklist for moving from React Router v7 to TanStack Router, covering routes, navigation, and search params. CX Codex +1 188installs bundle-size-optimization bundle-size-optimization — a skill that makes the agent measure TanStack Router client bundles and compare each candidate against a saved baseline. Useful when gzip creeps up after a change. CX Codex +1 139installs

Project sponsors

Companies that keep this analytics open