server-routes
БесплатноБез исполняемых скриптовНе проверенServer-side API endpoints using the server property on createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE), createHandlers for per-handler…
от TanStack★ 15 408 звёзд на GitHubОб этом скилле
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
// 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:
// 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:
// 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.tsroutes/users.index.tsroutes/users/index.ts
Handler Context
Each handler receives:
request— the incoming Request objectparams— dynamic path parameterscontext— context from middlewarepathname— the matched pathnamenext— call to fall through to SSR (returns aResponse)
Dynamic Path Params
// 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
// 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
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
// Using Response.json helper
handlers: {
GET: async () => {
return Response.json({ message: 'Hello!' })
},
}
Status Codes and Headers
handlers: {
GET: async ({ params }) => {
const user = await findUser(params.id)
if (!user) {
return new Response('Not found', { status: 404 })
}
return Response.json(user)
},
}
handlers: {
Установить server-routes в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл server-routes?
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.
Как установить скилл server-routes?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл server-routes запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic