Open History to see the last commit
1---
2id: server-routes
3title: Server Routes
4---
5β
6Server routes are a powerful feature of TanStack Start that allow you to create server-side endpoints in your application and are useful for handling raw HTTP requests, form submissions, user authentication, and much more.
7β
8Server routes can be defined in your `./src/routes` directory of your project **right alongside your TanStack Router routes** and are automatically handled by the TanStack Start server.
9β
10Here's what a simple server route looks like:
11β
12```ts
13// routes/hello.ts
14import { createFileRoute } from '@tanstack/react-router'
15β
16export const Route = createFileRoute('/hello')({
17 server: {
18 handlers: {
19 GET: async ({ request }) => {
20 return new Response('Hello, World!')
21 },
22 },
23 },
24})
25```
26β
27> [!NOTE]
28> Server routes are meant for HTTP endpoints that need to be called from outside your TanStack Start application. If you only need to call server-side logic from within your Start app and want Start to handle serialization for you, use [server functions](./server-functions) instead.
29β
30## Server Routes and App Routes
31β
32Because server routes can be defined in the same directory as your app routes, you can even use the same file for both!
33β
34```tsx
35// routes/hello.tsx
36import { createFileRoute } from '@tanstack/react-router'
37β
38export const Route = createFileRoute('/hello')({
39 server: {
40 handlers: {
41 POST: async ({ request }) => {
42 const body = await request.json()
43 return new Response(JSON.stringify({ message: `Hello, ${body.name}!` }))
44 },
45 },
46 },
47 component: HelloComponent,
48})
49β
50function HelloComponent() {
51 const [reply, setReply] = useState('')
52β
53 return (
54 <div>
55 <button
56 onClick={() => {
57 fetch('/hello', {
58 method: 'POST',
59 headers: {
60 'Content-Type': 'application/json',
61 },
62 body: JSON.stringify({ name: 'Tanner' }),
63 })
64 .then((res) => res.json())
65 .then((data) => setReply(data.message))
66 }}
67 >
68 Say Hello
69 </button>
70 </div>
71 )
72}
73```
74β
75## File Route Conventions
76β
77Server routes in TanStack Start follow the same file-based routing conventions as TanStack Router. This means that each file in your `routes` directory with a `server` property in the `createFileRoute` call will be treated as an API route. Here are a few examples:
78β
79- `/routes/users.ts` will create an API route at `/users`
80- `/routes/users.index.ts` will **also** create an API route at `/users` (but will error if duplicate methods are defined)
81- `/routes/users/$id.ts` will create an API route at `/users/$id`
82- `/routes/users/$id/posts.ts` will create an API route at `/users/$id/posts`
83- `/routes/users.$id.posts.ts` will create an API route at `/users/$id/posts`
84- `/routes/api/file/$.ts` will create an API route at `/api/file/$`
85- `/routes/my-script[.]js.ts` will create an API route at `/my-script.js`
86β
87## Unique Route Paths
88β
89Each route can only have a single handler file associated with it. So, if you have a file named `routes/users.ts` which'd equal the request path of `/users`, you cannot have other files that'd also resolve to the same route. For example, the following files would all resolve to the same route and would error:
90β
91- `/routes/users.index.ts`
92- `/routes/users.ts`
93- `/routes/users/index.ts`
94β
95## Escaped Matching
96β
97Just as with normal routes, server routes can match on escaped characters. For example, a file named `routes/users[.]json.ts` will create an API route at `/users.json`.
98β
99## Pathless Layout Routes and Break-out Routes
100β
101Because of the unified routing system, pathless layout routes and break-out routes are supported for similar functionality around server route middleware.
102β
103- Pathless layout routes can be used to add middleware to a group of routes
104- Break-out routes can be used to "break out" of parent middleware
105β
106## Nested Directories vs File-names
107β
108In the examples above, you may have noticed that the file naming conventions are flexible and allow you to mix and match directories and file names. This is intentional and allows you to organize your Server routes in a way that makes sense for your application. You can read more about this in the [TanStack Router File-based Routing Guide](/router/latest/docs/framework/react/routing/file-based-routing#s-or-s).
109β
110## Handling Server Route Requests
111β
112Server route requests are handled by Start automatically by default or by Start's `createStartHandler` in your custom `src/server.ts` entry point file.
113β
114The start handler is responsible for matching an incoming request to a server route and executing the appropriate middleware and handler.
115β
116If you need to customize the server handler, you can do so by creating a custom handler and then passing the event to the start handler. See [The Server Entry Point](./server-entry-point).
117β
118## Defining a Server Route
119β
120Server routes are created by adding a `server` property to your `createFileRoute` call. The `server` property contains:
121β
122- `handlers` - Either an object mapping HTTP methods to handler functions, or a function that receives `createHandlers` for more advanced use cases
123- `middleware` - Optional route-level middleware array that applies to all handlers
124β
125```ts
126// routes/hello.ts
127import { createFileRoute } from '@tanstack/react-router'
128β
129export const Route = createFileRoute('/hello')({
130 server: {
131 handlers: {
132 GET: async ({ request }) => {
133 return new Response('Hello, World! from ' + request.url)
134 },
135 },
136 },
137})
138```
139β
140## Defining Server Route Handlers
141β
142You can define handlers in two ways:
143β
144- **Simple handlers**: Provide handler functions directly in a handlers object
145- **Handlers with middleware**: Use the `createHandlers` function to define handlers with middleware
146β
147### Simple handlers
148β
149For simple use cases, you can provide handler functions directly in a handlers object.
150β
151```ts
152// routes/hello.ts
153import { createFileRoute } from '@tanstack/react-router'
154β
155export const Route = createFileRoute('/hello')({
156 server: {
157 handlers: {
158 GET: async ({ request }) => {
159 return new Response('Hello, World! from ' + request.url)
160 },
161 },
162 },
163})
164```
165β
166### Adding middleware to specific handlers
167β
168For more complex use cases, you can add middleware to specific handlers. This requires using the `createHandlers` function:
169β
170```tsx
171// routes/hello.ts
172import { createFileRoute } from '@tanstack/react-router'
173β
174export const Route = createFileRoute('/hello')({
175 server: {
176 handlers: ({ createHandlers }) =>
177 createHandlers({
178 GET: {
179 middleware: [loggerMiddleware],
180 handler: async ({ request }) => {
181 return new Response('Hello, World! from ' + request.url)
182 },
183 },
184 }),
185 },
186})
187```
188β
189### Adding middleware to all handlers
190β
191You can also add middleware that applies to all handlers in a route by using the `middleware` property at the server level:
192β
193```tsx
194// routes/hello.ts
195import { createFileRoute } from '@tanstack/react-router'
196β
197export const Route = createFileRoute('/hello')({
198 server: {
199 middleware: [authMiddleware, loggerMiddleware], // Applies to all handlers
200 handlers: {
201 GET: async ({ request }) => {
202 return new Response('Hello, World! from ' + request.url)
203 },
204 POST: async ({ request }) => {
205 const body = await request.json()
206 return new Response(`Hello, ${body.name}!`)
207 },
208 },
209 },
210})
211```
212β
213### Combining route-level and handler-specific middleware
214β
215You can combine both approaches - route-level middleware will run first, followed by handler-specific middleware:
216β
217```tsx
218// routes/hello.ts
219import { createFileRoute } from '@tanstack/react-router'
220β
221export const Route = createFileRoute('/hello')({
222 server: {
223 middleware: [authMiddleware], // Runs first for all handlers
224 handlers: ({ createHandlers }) =>
225 createHandlers({
226 GET: async ({ request }) => {
227 return new Response('Hello, World!')
228 },
229 POST: {
230 middleware: [validationMiddleware], // Runs after authMiddleware, only for POST
231 handler: async ({ request }) => {
232 const body = await request.json()
233 return new Response(`Hello, ${body.name}!`)
234 },
235 },
236 }),
237 },
238})
239```
240β
241## Handler Context
242β
243Each HTTP method handler receives an object with the following properties:
244β
245- `request`: The incoming request object. You can read more about the `Request` object in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Request).
246- `params`: An object containing the dynamic path parameters of the route. For example, if the route path is `/users/$id`, and the request is made to `/users/123`, then `params` will be `{ id: '123' }`. We'll cover dynamic path parameters and wildcard parameters later in this guide.
247- `context`: An object containing the context of the request. This is useful for passing data between middleware.
248β
249Once you've processed the request, you can return a `Response` object or `Promise<Response>` or even use any of the helpers from `@tanstack/react-start` to manipulate the response.
250β
251## Dynamic Path Params
252β
253Server routes support dynamic path parameters in the same way as TanStack Router. For example, a file named `routes/users/$id.ts` will create an API route at `/users/$id` that accepts a dynamic `id` parameter.
254β
255```ts
256// routes/users/$id.ts
257import { createFileRoute } from '@tanstack/react-router'
258β
259export const Route = createFileRoute('/users/$id')({
260 server: {
261 handlers: {
262 GET: async ({ params }) => {
263 const { id } = params
264 return new Response(`User ID: ${id}`)
265 },
266 },
267 },
268})
269β
270// Visit /users/123 to see the response
271// User ID: 123
272```
273β
274You can also have multiple dynamic path parameters in a single route. For example, a file named `routes/users/$id/posts/$postId.ts` will create an API route at `/users/$id/posts/$postId` that accepts two dynamic parameters.
275β
276```ts
277// routes/users/$id/posts/$postId.ts
278import { createFileRoute } from '@tanstack/react-router'
279β
280export const Route = createFileRoute('/users/$id/posts/$postId')({
281 server: {
282 handlers: {
283 GET: async ({ params }) => {
284 const { id, postId } = params
285 return new Response(`User ID: ${id}, Post ID: ${postId}`)
286 },
287 },
288 },
289})
290β
291// Visit /users/123/posts/456 to see the response
292// User ID: 123, Post ID: 456
293```
294β
295## Wildcard/Splat Param
296β
297Server routes also support wildcard parameters at the end of the path, which are denoted by a `$` followed by nothing. For example, a file named `routes/file/$.ts` will create an API route at `/file/$` that accepts a wildcard parameter.
298β
299```ts
300// routes/file/$.ts
301import { createFileRoute } from '@tanstack/react-router'
302β
303export const Route = createFileRoute('/file/$')({
304 server: {
305 handlers: {
306 GET: async ({ params }) => {
307 const { _splat } = params
308 return new Response(`File: ${_splat}`)
309 },
310 },
311 },
312})
313β
314// Visit /file/hello.txt to see the response
315// File: hello.txt
316```
317β
318## Handling requests with a body
319β
320To handle POST requests, you can add a `POST` handler to the route object. The handler will receive the request object as the first argument, and you can access the request body using the `request.json()` method.
321β
322```ts
323// routes/hello.ts
324import { createFileRoute } from '@tanstack/react-router'
325β
326export const Route = createFileRoute('/hello')({
327 server: {
328 handlers: {
329 POST: async ({ request }) => {
330 const body = await request.json()
331 return new Response(`Hello, ${body.name}!`)
332 },
333 },
334 },
335})
336β
337// Send a POST request to /hello with a JSON body like { "name": "Tanner" }
338// Hello, Tanner!
339```
340β
341This also applies to other HTTP methods like `PUT`, `PATCH`, and `DELETE`. You can add handlers for these methods in the route object and access the request body using the appropriate method.
342β
343It's important to remember that the `request.json()` method returns a `Promise` that resolves to the parsed JSON body of the request. You need to `await` the result to access the body.
344β
345This is a common pattern for handling POST requests in Server routes/ You can also use other methods like `request.text()` or `request.formData()` to access the body of the request.
346β
347## Responding with JSON
348β
349When returning JSON using a Response object, this is a common pattern:
350β
351```ts
352// routes/hello.ts
353import { createFileRoute } from '@tanstack/react-router'
354β
355export const Route = createFileRoute('/hello')({
356 server: {
357 handlers: {
358 GET: async ({ request }) => {
359 return new Response(JSON.stringify({ message: 'Hello, World!' }), {
360 headers: {
361 'Content-Type': 'application/json',
362 },
363 })
364 },
365 },
366 },
367})
368β
369// Visit /hello to see the response
370// {"message":"Hello, World!"}
371```
372β
373## Using the `Response.json` helper function
374β
375Or you can use the [`Response.json`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static) helper function to automatically set the `Content-Type` header to `application/json` and serialize the JSON object for you.
376β
377```ts
378// routes/hello.ts
379import { createFileRoute } from '@tanstack/react-router'
380β
381export const Route = createFileRoute('/hello')({
382 server: {
383 handlers: {
384 GET: async ({ request }) => {
385 return Response.json({ message: 'Hello, World!' })
386 },
387 },
388 },
389})
390β
391// Visit /hello to see the response
392// {"message":"Hello, World!"}
393```
394β
395## Responding with a status code
396β
397You can set the status code of the response by passing it as a property of the second argument to the `Response` constructor
398β
399```ts
400// routes/hello.ts
401import { createFileRoute } from '@tanstack/react-router'
402β
403export const Route = createFileRoute('/hello')({
404 server: {
405 handlers: {
406 GET: async ({ request, params }) => {
407 const user = await findUser(params.id)
408 if (!user) {
409 return new Response('User not found', {
410 status: 404,
411 })
412 }
413 return Response.json(user)
414 },
415 },
416 },
417})
418```
419β
420In this example, we're returning a `404` status code if the user is not found. You can set any valid HTTP status code using this method.
421β
422## Setting headers in the response
423β
424Sometimes you may need to set headers in the response. You can do this by passing an object as the second argument to the `Response` constructor.
425β
426```ts
427// routes/hello.ts
428import { createFileRoute } from '@tanstack/react-router'
429export const Route = createFileRoute('/hello')({
430 server: {
431 handlers: {
432 GET: async ({ request }) => {
433 return new Response('Hello, World!', {
434 headers: {
435 'Content-Type': 'text/plain',
436 },
437 })
438 },
439 },
440 },
441})
442// Visit /hello to see the response
443// Hello, World!
444```