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

createStartHandler.ts

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