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

request-response.ts

462 lines12.2 KB

1import { AsyncLocalStorage } from 'node:async_hooks'
2​
3import {
4 H3Event,
5 clearSession as h3_clearSession,
6 deleteCookie as h3_deleteCookie,
7 getRequestHost as h3_getRequestHost,
8 getRequestIP as h3_getRequestIP,
9 getRequestProtocol as h3_getRequestProtocol,
10 getRequestURL as h3_getRequestURL,
11 getSession as h3_getSession,
12 getValidatedQuery as h3_getValidatedQuery,
13 parseCookies as h3_parseCookies,
14 sanitizeStatusCode as h3_sanitizeStatusCode,
15 sanitizeStatusMessage as h3_sanitizeStatusMessage,
16 sealSession as h3_sealSession,
17 setCookie as h3_setCookie,
18 toResponse as h3_toResponse,
19 unsealSession as h3_unsealSession,
20 updateSession as h3_updateSession,
21 useSession as h3_useSession,
22} from 'h3-v2'
23import type {
24 RequestHeaderMap,
25 RequestHeaderName,
26 ResponseHeaderMap,
27 ResponseHeaderName,
28 TypedHeaders,
29} from 'fetchdts'
30​
31import type { CookieSerializeOptions } from 'cookie-es'
32import type {
33 Session,
34 SessionConfig,
35 SessionData,
36 SessionManager,
37 SessionUpdate,
38} from './session'
39import type { StandardSchemaV1 } from '@standard-schema/spec'
40import type { RequestHandler } from './request-handler'
41​
42interface StartEvent {
43 h3Event: H3Event
45​
46// Use a global symbol to ensure the same AsyncLocalStorage instance is shared
47// across different bundles that may each bundle this module.
48const GLOBAL_EVENT_STORAGE_KEY = Symbol.for('tanstack-start:event-storage')
49​
50const globalObj = globalThis as typeof globalThis & {
51 [GLOBAL_EVENT_STORAGE_KEY]?: AsyncLocalStorage<StartEvent>
53​
54if (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {
55 globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage<StartEvent>()
57​
58const eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY]
59​
60export type { ResponseHeaderName, RequestHeaderName }
61​
62type HeadersWithGetSetCookie = Headers & {
63 getSetCookie?: () => Array<string>
65​
66type MaybePromise<T> = T | Promise<T>
67​
68function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
69 return (
70 (typeof value === 'object' || typeof value === 'function') &&
71 value !== null &&
72 typeof (value as PromiseLike<unknown>).then === 'function'
73 )
75​
76function getSetCookieValues(headers: Headers): Array<string> {
77 const headersWithSetCookie = headers as HeadersWithGetSetCookie
78 if (typeof headersWithSetCookie.getSetCookie === 'function') {
79 return headersWithSetCookie.getSetCookie()
80 }
81 const value = headers.get('set-cookie')
82 return value ? [value] : []
84​
85function mergeEventResponseHeaders(response: Response, event: H3Event): void {
86 if (response.ok) {
87 return
88 }
89​
90 const eventSetCookies = getSetCookieValues(event.res.headers)
91 if (eventSetCookies.length === 0) {
92 return
93 }
94​
95 const responseSetCookies = getSetCookieValues(response.headers)
96 response.headers.delete('set-cookie')
97 for (const cookie of responseSetCookies) {
98 response.headers.append('set-cookie', cookie)
99 }
100 for (const cookie of eventSetCookies) {
101 response.headers.append('set-cookie', cookie)
102 }
104​
105function finalizeResponse(value: unknown, event: H3Event): Response {
106 const response = ensureResponse(value)
107 mergeEventResponseHeaders(response, event)
108 return response
110​
111function finalizeMaybeResponse(
112 value: unknown,
113 event: H3Event,
114): MaybePromise<Response> {
115 if (isPromiseLike(value)) {
116 return Promise.resolve(value).then(
117 (resolved) => finalizeResponse(resolved, event),
118 (error) => finalizeResponse(handleResponseError(error), event),
119 )
120 }
121​
122 return finalizeResponse(value, event)
124​
125function ensureResponse(value: unknown): Response {
126 if (value instanceof Response) {
127 return value
128 }
129​
130 return new Response('Internal Server Error', { status: 500 })
132​
133function handleResponseError(error: unknown): Response {
134 if (error instanceof Response) {
135 return error
136 }
137 if (error instanceof Error) {
138 throw error
139 }
140​
141 return new Response('Internal Server Error', { status: 500 })
143​
144export function requestHandler<TRegister = unknown>(
145 handler: RequestHandler<TRegister>,
146) {
147 return (request: Request, requestOpts: any): Promise<Response> | Response => {
148 let h3Event: H3Event
149 try {
150 h3Event = new H3Event(request)
151 } catch (error) {
152 if (error instanceof URIError) {
153 return new Response(null, {
154 status: 400,
155 statusText: 'Bad Request',
156 })
157 }
158 throw error
159 }
160​
161 let response: unknown
162 try {
163 response = eventStorage.run({ h3Event }, () =>
164 handler(request, requestOpts),
165 )
166 } catch (error) {
167 response = handleResponseError(error)
168 }
169 return h3_toResponse(finalizeMaybeResponse(response, h3Event), h3Event)
170 }
172​
173function getH3Event() {
174 const event = eventStorage.getStore()
175 if (!event) {
176 throw new Error(
177 `No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,
178 )
179 }
180 return event.h3Event
182​
183export function getRequest(): Request {
184 const event = getH3Event()
185 return event.req
187​
188export function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {
189 return getH3Event().req.headers
191​
192export function getRequestHeader(name: RequestHeaderName): string | undefined {
193 return getRequestHeaders().get(name) || undefined
195​
196export function getRequestIP(opts?: {
197 /**
198 * Use the X-Forwarded-For HTTP header set by proxies.
199 *
200 * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.
201 */
202 xForwardedFor?: boolean
203}) {
204 return h3_getRequestIP(getH3Event(), opts)
206​
207/**
208 * Get the request hostname.
209 *
210 * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
211 *
212 * If no host header is found, it will default to "localhost".
213 */
214export function getRequestHost(opts?: { xForwardedHost?: boolean }) {
215 return h3_getRequestHost(getH3Event(), opts)
217​
218/**
219 * Get the full incoming request URL.
220 *
221 * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
222 *
223 * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.
224 */
225export function getRequestUrl(opts?: {
226 xForwardedHost?: boolean
227 xForwardedProto?: boolean
228}) {
229 return h3_getRequestURL(getH3Event(), opts)
231​
232/**
233 * Get the request protocol.
234 *
235 * If `x-forwarded-proto` header is set to "https", it will return "https". You can disable this behavior by setting `xForwardedProto` to `false`.
236 *
237 * If protocol cannot be determined, it will default to "http".
238 */
239export function getRequestProtocol(opts?: {
240 xForwardedProto?: boolean
241}): 'http' | 'https' | (string & {}) {
242 return h3_getRequestProtocol(getH3Event(), opts)
244​
245export function setResponseHeaders(
246 headers: TypedHeaders<ResponseHeaderMap>,
247): void {
248 const event = getH3Event()
249 if (event.res.headers === headers) {
250 return
251 }
252 let previousName = ''
253 // Headers iteration groups entries by name, including separate Set-Cookie values.
254 for (const [name, value] of headers) {
255 event.res.headers[name === previousName ? 'append' : 'set'](name, value)
256 previousName = name
257 }
259​
260export function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {
261 const event = getH3Event()
262 return event.res.headers
264​
265export function getResponseHeader(
266 name: ResponseHeaderName,
267): string | undefined {
268 const event = getH3Event()
269 return event.res.headers.get(name) || undefined
271​
272export function setResponseHeader(
273 name: ResponseHeaderName,
274 value: string | Array<string>,
275): void {
276 const event = getH3Event()
277 if (Array.isArray(value)) {
278 event.res.headers.delete(name)
279 for (const valueItem of value) {
280 event.res.headers.append(name, valueItem)
281 }
282 } else {
283 event.res.headers.set(name, value)
284 }
286export function removeResponseHeader(name: ResponseHeaderName): void {
287 const event = getH3Event()
288 event.res.headers.delete(name)
290​
291export function clearResponseHeaders(
292 headerNames?: Array<ResponseHeaderName>,
293): void {
294 const event = getH3Event()
295 // If headerNames is provided, clear only those headers
296 if (headerNames && headerNames.length > 0) {
297 for (const name of headerNames) {
298 event.res.headers.delete(name)
299 }
300 // Otherwise, clear all headers
301 } else {
302 for (const name of event.res.headers.keys()) {
303 event.res.headers.delete(name)
304 }
305 }
307​
308export function getResponseStatus(): number {
309 return getH3Event().res.status || 200
311​
312export function setResponseStatus(code?: number, text?: string): void {
313 const event = getH3Event()
314 if (code) {
315 event.res.status = h3_sanitizeStatusCode(code, event.res.status)
316 }
317 if (text) {
318 event.res.statusText = h3_sanitizeStatusMessage(text)
319 }
321​
322/**
323 * Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.
324 * @returns Object of cookie name-value pairs
325 * ```ts
326 * const cookies = getCookies()
327 * ```
328 */
329export function getCookies(): Record<string, string> {
330 const event = getH3Event()
331 const cookies = h3_parseCookies(event)
332 const definedCookies: Record<string, string> = Object.create(null)
333​
334 for (const [name, value] of Object.entries(cookies)) {
335 if (value !== undefined) {
336 definedCookies[name] = value
337 }
338 }
339​
340 return definedCookies
342​
343/**
344 * Get a cookie value by name.
345 * @param name Name of the cookie to get
346 * @returns {*} Value of the cookie (String or undefined)
347 * ```ts
348 * const authorization = getCookie('Authorization')
349 * ```
350 */
351export function getCookie(name: string): string | undefined {
352 return getCookies()[name]
354​
355/**
356 * Set a cookie value by name.
357 * @param name Name of the cookie to set
358 * @param value Value of the cookie to set
359 * @param options {CookieSerializeOptions} Options for serializing the cookie
360 * ```ts
361 * setCookie('Authorization', '1234567')
362 * ```
363 */
364export function setCookie(
365 name: string,
366 value: string,
367 options?: CookieSerializeOptions,
368): void {
369 const event = getH3Event()
370 h3_setCookie(event, name, value, options)
372​
373/**
374 * Remove a cookie by name.
375 * @param name Name of the cookie to delete
376 * @param serializeOptions {CookieSerializeOptions} Cookie options
377 * ```ts
378 * deleteCookie('SessionId')
379 * ```
380 */
381export function deleteCookie(
382 name: string,
383 options?: CookieSerializeOptions,
384): void {
385 const event = getH3Event()
386 h3_deleteCookie(event, name, options)
388​
389function getDefaultSessionConfig(config: SessionConfig): SessionConfig {
390 return {
391 name: 'start',
392 ...config,
393 }
395​
396/**
397 * Create a session manager for the current request.
398 */
399export function useSession<TSessionData extends SessionData = SessionData>(
400 config: SessionConfig,
401): Promise<SessionManager<TSessionData>> {
402 const event = getH3Event()
403 return h3_useSession(event, getDefaultSessionConfig(config))
405/**
406 * Get the session for the current request
407 */
408export function getSession<TSessionData extends SessionData = SessionData>(
409 config: SessionConfig,
410): Promise<Session<TSessionData>> {
411 const event = getH3Event()
412 return h3_getSession(event, getDefaultSessionConfig(config))
414​
415/**
416 * Update the session data for the current request.
417 */
418export function updateSession<TSessionData extends SessionData = SessionData>(
419 config: SessionConfig,
420 update?: SessionUpdate<TSessionData>,
421): Promise<Session<TSessionData>> {
422 const event = getH3Event()
423 return h3_updateSession(event, getDefaultSessionConfig(config), update)
425​
426/**
427 * Encrypt and sign the session data for the current request.
428 */
429export function sealSession(config: SessionConfig): Promise<string> {
430 const event = getH3Event()
431 return h3_sealSession(event, getDefaultSessionConfig(config))
433/**
434 * Decrypt and verify the session data for the current request.
435 */
436export function unsealSession(
437 config: SessionConfig,
438 sealed: string,
439): Promise<Partial<Session>> {
440 const event = getH3Event()
441 return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)
443​
444/**
445 * Clear the session data for the current request.
446 */
447export function clearSession(config: Partial<SessionConfig>): Promise<void> {
448 const event = getH3Event()
449 return h3_clearSession(event, { name: 'start', ...config })
451​
452export function getResponse() {
453 const event = getH3Event()
454 return event.res
456​
457// not public API (yet)
458export function getValidatedQuery<TSchema extends StandardSchemaV1>(
459 schema: StandardSchemaV1,
460): Promise<StandardSchemaV1.InferOutput<TSchema>> {
461 return h3_getValidatedQuery(getH3Event(), schema)