Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

server-routes.md

444 lines14.4 KB

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 )
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```