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

createStartHandler.ts

510 lines15.6 KB

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