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

createStartHandler.ts

553 lines16.3 KB

1import { createMemoryHistory } from '@tanstack/history'
2import {
3 flattenMiddlewares,
4 json,
5 mergeHeaders,
6} from '@tanstack/start-client-core'
7import {
8 executeRewriteInput,
9 isRedirect,
10 isResolvedRedirect,
11 joinPaths,
12 trimPath,
13} from '@tanstack/router-core'
14import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server'
15import { runWithStartContext } from '@tanstack/start-storage-context'
16import { getResponseHeaders, requestHandler } from './request-response'
17import { getStartManifest } from './router-manifest'
18import { handleServerAction } from './server-functions-handler'
19​
20import { HEADERS } from './constants'
21import { ServerFunctionSerializationAdapter } from './serializer/ServerFunctionSerializationAdapter'
22import type {
23 AnyStartInstanceOptions,
24 RouteMethod,
25 RouteMethodHandlerFn,
26 RouterEntry,
27 StartEntry,
28} from '@tanstack/start-client-core'
29import type { RequestHandler } from './request-handler'
30import type {
31 AnyRoute,
32 AnyRouter,
33 Awaitable,
34 Manifest,
35 Register,
36} from '@tanstack/router-core'
37import type { HandlerCallback } from '@tanstack/router-core/ssr/server'
38​
39type TODO = any
40​
41function getStartResponseHeaders(opts: { router: AnyRouter }) {
42 const headers = mergeHeaders(
43 getResponseHeaders() as Headers,
44 {
45 'Content-Type': 'text/html; charset=utf-8',
46 },
47 ...opts.router.state.matches.map((match) => {
48 return match.headers
49 }),
50 )
51 return headers
53​
54export function createStartHandler<TRegister = Register>(
55 cb: HandlerCallback<AnyRouter>,
56): RequestHandler<TRegister> {
57 if (!process.env.TSS_SERVER_FN_BASE) {
58 throw new Error(
59 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',
60 )
61 }
62 // TODO do we remove this?
63 const APP_BASE = process.env.TSS_APP_BASE || '/'
64 // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE
65 const serverFnBase = joinPaths([
66 APP_BASE,
67 trimPath(process.env.TSS_SERVER_FN_BASE),
68 '/',
69 ])
70 let startRoutesManifest: Manifest | null = null
71 let startEntry: StartEntry | null = null
72 let routerEntry: RouterEntry | null = null
73 const getEntries = async (): Promise<{
74 startEntry: StartEntry
75 routerEntry: RouterEntry
76 }> => {
77 if (routerEntry === null) {
78 // @ts-ignore when building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core
79 routerEntry = await import('#tanstack-router-entry')
80 }
81 if (startEntry === null) {
82 // @ts-ignore when building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core
83 startEntry = await import('#tanstack-start-entry')
84 }
85 return {
86 startEntry: startEntry as unknown as StartEntry,
87 routerEntry: routerEntry as unknown as RouterEntry,
88 }
89 }
90​
91 const originalFetch = globalThis.fetch
92​
93 const startRequestResolver: RequestHandler<Register> = async (
94 request,
95 requestOpts,
96 ) => {
97 function getOrigin() {
98 const originHeader = request.headers.get('Origin')
99 if (originHeader) {
100 return originHeader
101 }
102 try {
103 return new URL(request.url).origin
104 } catch {}
105 return 'http://localhost'
106 }
107​
108 // Patching fetch function to use our request resolver
109 // if the input starts with `/` which is a common pattern for
110 // client-side routing.
111 // When we encounter similar requests, we can assume that the
112 // user wants to use the same origin as the current request.
113 globalThis.fetch = async function (input, init) {
114 function resolve(url: URL, requestOptions: RequestInit | undefined) {
115 const fetchRequest = new Request(url, requestOptions)
116 return startRequestResolver(fetchRequest, requestOpts)
117 }
118​
119 if (typeof input === 'string' && input.startsWith('/')) {
120 // e.g: fetch('/api/data')
121 const url = new URL(input, getOrigin())
122 return resolve(url, init)
123 } else if (
124 typeof input === 'object' &&
125 'url' in input &&
126 typeof input.url === 'string' &&
127 input.url.startsWith('/')
128 ) {
129 // e.g: fetch(new Request('/api/data'))
130 const url = new URL(input.url, getOrigin())
131 return resolve(url, init)
132 }
133​
134 // If not, it should just use the original fetch
135 return originalFetch(input, init)
136 } as typeof fetch
137​
138 const url = new URL(request.url)
139 const href = url.href.replace(url.origin, '')
140​
141 let router: AnyRouter | null = null
142 const getRouter = async () => {
143 if (router) return router
144 // TODO how does this work with base path? does the router need to be configured the same as APP_BASE?
145 router = await (await getEntries()).routerEntry.getRouter()
146​
147 // Update the client-side router with the history
148 const isPrerendering = process.env.TSS_PRERENDERING === 'true'
149 // env var is set during dev is SPA mode is enabled
150 let isShell = process.env.TSS_SHELL === 'true'
151 if (isPrerendering && !isShell) {
152 // only read the shell header if we are prerendering
153 // to avoid runtime behavior changes by injecting this header
154 // the header is set by the prerender plugin
155 isShell = request.headers.get(HEADERS.TSS_SHELL) === 'true'
156 }
157​
158 // Create a history for the client-side router
159 const history = createMemoryHistory({
160 initialEntries: [href],
161 })
162​
163 const origin = router.options.origin ?? getOrigin()
164 router.update({
165 history,
166 isShell,
167 isPrerendering,
168 origin,
169 ...{
170 defaultSsr: startOptions.defaultSsr,
171 serializationAdapters: startOptions.serializationAdapters,
172 },
173 })
174 return router
175 }
176​
177 const startOptions: AnyStartInstanceOptions =
178 (await (await getEntries()).startEntry.startInstance?.getOptions()) ||
179 ({} as AnyStartInstanceOptions)
180 startOptions.serializationAdapters =
181 startOptions.serializationAdapters || []
182 // insert start specific default serialization adapters
183 startOptions.serializationAdapters.push(ServerFunctionSerializationAdapter)
184​
185 const requestHandlerMiddleware = handlerToMiddleware(
186 async ({ context }) => {
187 const response = await runWithStartContext(
188 {
189 getRouter,
190 startOptions,
191 contextAfterGlobalMiddlewares: context,
192 },
193 async () => {
194 try {
195 // First, let's attempt to handle server functions
196 if (href.startsWith(serverFnBase)) {
197 return await handleServerAction({
198 request,
199 context: requestOpts?.context,
200 })
201 }
202​
203 const executeRouter = async ({
204 serverContext,
205 }: {
206 serverContext: any
207 }) => {
208 const requestAcceptHeader =
209 request.headers.get('Accept') || '*/*'
210 const splitRequestAcceptHeader = requestAcceptHeader.split(',')
211​
212 const supportedMimeTypes = ['*/*', 'text/html']
213 const isRouterAcceptSupported = supportedMimeTypes.some(
214 (mimeType) =>
215 splitRequestAcceptHeader.some((acceptedMimeType) =>
216 acceptedMimeType.trim().startsWith(mimeType),
217 ),
218 )
219​
220 if (!isRouterAcceptSupported) {
221 return json(
222 {
223 error: 'Only HTML requests are supported here',
224 },
225 {
226 status: 500,
227 },
228 )
229 }
230​
231 // if the startRoutesManifest is not loaded yet, load it once
232 if (startRoutesManifest === null) {
233 startRoutesManifest = await getStartManifest({
234 basePath: APP_BASE,
235 })
236 }
237 const router = await getRouter()
238 attachRouterServerSsrUtils({
239 router,
240 manifest: startRoutesManifest,
241 })
242​
243 router.update({ additionalContext: { serverContext } })
244 await router.load()
245​
246 // If there was a redirect, skip rendering the page at all
247 if (router.state.redirect) {
248 return router.state.redirect
249 }
250​
251 await router.serverSsr!.dehydrate()
252​
253 const responseHeaders = getStartResponseHeaders({ router })
254 const response = await cb({
255 request,
256 router,
257 responseHeaders,
258 })
259​
260 return response
261 }
262​
263 const response = await handleServerRoutes({
264 getRouter,
265 request,
266 executeRouter,
267 })
268​
269 return response
270 } catch (err) {
271 if (err instanceof Response) {
272 return err
273 }
274​
275 throw err
276 }
277 },
278 )
279 return response
280 },
281 )
282​
283 const flattenedMiddlewares = startOptions.requestMiddleware
284 ? flattenMiddlewares(startOptions.requestMiddleware)
285 : []
286 const middlewares = flattenedMiddlewares.map((d) => d.options.server)
287 const ctx = await executeMiddleware(
288 [...middlewares, requestHandlerMiddleware],
289 {
290 request,
291​
292 context: requestOpts?.context || {},
293 },
294 )
295​
296 const response: Response = ctx.response
297​
298 if (isRedirect(response)) {
299 if (isResolvedRedirect(response)) {
300 if (request.headers.get('x-tsr-redirect') === 'manual') {
301 return json(
302 {
303 ...response.options,
304 isSerializedRedirect: true,
305 },
306 {
307 headers: response.headers,
308 },
309 )
310 }
311 return response
312 }
313 if (
314 response.options.to &&
315 typeof response.options.to === 'string' &&
316 !response.options.to.startsWith('/')
317 ) {
318 throw new Error(
319 `Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(response.options)}`,
320 )
321 }
322​
323 if (
324 ['params', 'search', 'hash'].some(
325 (d) => typeof (response.options as any)[d] === 'function',
326 )
327 ) {
328 throw new Error(
329 `Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(
330 response.options,
331 )
332 .filter((d) => typeof (response.options as any)[d] === 'function')
333 .map((d) => `"${d}"`)
334 .join(', ')}`,
335 )
336 }
337​
338 const router = await getRouter()
339 const redirect = router.resolveRedirect(response)
340​
341 if (request.headers.get('x-tsr-redirect') === 'manual') {
342 return json(
343 {
344 ...response.options,
345 isSerializedRedirect: true,
346 },
347 {
348 headers: response.headers,
349 },
350 )
351 }
352​
353 return redirect
354 }
355​
356 return response
357 }
358​
359 return requestHandler(startRequestResolver)
361​
362async function handleServerRoutes({
363 getRouter,
364 request,
365 executeRouter,
366}: {
367 getRouter: () => Awaitable<AnyRouter>
368 request: Request
369 executeRouter: ({
370 serverContext,
371 }: {
372 serverContext: any
373 }) => Promise<Response>
374}) {
375 const router = await getRouter()
376 let url = new URL(request.url)
377 url = executeRewriteInput(router.rewrite, url)
378 const pathname = url.pathname
379 const { matchedRoutes, foundRoute, routeParams } = router.getMatchedRoutes(
380 pathname,
381 undefined,
382 )
383​
384 // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?
385​
386 const middlewares = flattenMiddlewares(
387 matchedRoutes.flatMap((r) => r.options.server?.middleware).filter(Boolean),
388 ).map((d) => d.options.server)
389​
390 const server = foundRoute?.options.server
391​
392 if (server) {
393 if (server.handlers) {
394 const handlers =
395 typeof server.handlers === 'function'
396 ? server.handlers({
397 createHandlers: (d: any) => d,
398 })
399 : server.handlers
400​
401 const requestMethod = request.method.toLowerCase()
402​
403 // Attempt to find the method in the handlers
404 let method = Object.keys(handlers).find(
405 (method) => method.toLowerCase() === requestMethod,
406 )
407​
408 // If no method is found, attempt to find the 'all' method
409 if (!method) {
410 method = Object.keys(handlers).find(
411 (method) => method.toLowerCase() === 'all',
412 )
413 ? 'all'
414 : undefined
415 }
416​
417 // If a method is found, execute the handler
418 if (method) {
419 const handler = handlers[method as RouteMethod]
420 if (handler) {
421 const mayDefer = !!foundRoute.options.component
422 if (typeof handler === 'function') {
423 middlewares.push(handlerToMiddleware(handler, mayDefer))
424 } else {
425 const { middleware } = handler
426 if (middleware && middleware.length) {
427 middlewares.push(
428 ...flattenMiddlewares(middleware).map((d) => d.options.server),
429 )
430 }
431 if (handler.handler) {
432 middlewares.push(handlerToMiddleware(handler.handler, mayDefer))
433 }
434 }
435 }
436 }
437 }
438 }
439​
440 // eventually, execute the router
441 middlewares.push(
442 handlerToMiddleware((ctx) => executeRouter({ serverContext: ctx.context })),
443 )
444​
445 const ctx = await executeMiddleware(middlewares, {
446 request,
447 context: {},
448 params: routeParams,
449 pathname,
450 })
451​
452 const response: Response = ctx.response
453​
454 return response
456​
457function throwRouteHandlerError() {
458 if (process.env.NODE_ENV === 'development') {
459 throw new Error(
460 `It looks like you forgot to return a response from your server route handler. If you want to defer to the app router, make sure to have a component set in this route.`,
461 )
462 }
463 throw new Error('Internal Server Error')
465​
466function throwIfMayNotDefer() {
467 if (process.env.NODE_ENV === 'development') {
468 throw new Error(
469 `You cannot defer to the app router if there is no component defined on this route.`,
470 )
471 }
472 throw new Error('Internal Server Error')
474function handlerToMiddleware(
475 handler: RouteMethodHandlerFn<any, AnyRoute, any, any, any, any>,
476 mayDefer: boolean = false,
477) {
478 if (mayDefer) {
479 return handler as TODO
480 }
481 return async ({ next: _next, ...rest }: TODO) => {
482 const response = await handler({ ...rest, next: throwIfMayNotDefer })
483 if (!response) {
484 throwRouteHandlerError()
485 }
486 return response
487 }
489​
490function executeMiddleware(middlewares: TODO, ctx: TODO) {
491 let index = -1
492​
493 const next = async (ctx: TODO) => {
494 index++
495 const middleware = middlewares[index]
496 if (!middleware) return ctx
497​
498 let result
499 try {
500 result = await middleware({
501 ...ctx,
502 // Allow the middleware to call the next middleware in the chain
503 next: async (nextCtx: TODO) => {
504 // Allow the caller to extend the context for the next middleware
505 const nextResult = await next({
506 ...ctx,
507 ...nextCtx,
508 context: {
509 ...ctx.context,
510 ...(nextCtx?.context || {}),
511 },
512 })
513​
514 // Merge the result into the context\
515 return Object.assign(ctx, handleCtxResult(nextResult))
516 },
517 // Allow the middleware result to extend the return context
518 })
519 } catch (err: TODO) {
520 if (isSpecialResponse(err)) {
521 result = {
522 response: err,
523 }
524 } else {
525 throw err
526 }
527 }
528​
529 // Merge the middleware result into the context, just in case it
530 // returns a partial context
531 return Object.assign(ctx, handleCtxResult(result))
532 }
533​
534 return handleCtxResult(next(ctx))
536​
537function handleCtxResult(result: TODO) {
538 if (isSpecialResponse(result)) {
539 return {
540 response: result,
541 }
542 }
543​
544 return result
546​
547function isSpecialResponse(err: TODO) {
548 return isResponse(err) || isRedirect(err)
550​
551function isResponse(response: Response): response is Response {
552 return response instanceof Response