Open History to see the last commit
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
44}
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>
52}
53β
54if (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {
55 globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage<StartEvent>()
56}
57β
58const eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY]
59β
60export type { ResponseHeaderName, RequestHeaderName }
61β
62type HeadersWithGetSetCookie = Headers & {
63 getSetCookie?: () => Array<string>
64}
65β
66type MaybePromise<T> = T | Promise<T>
67β
68function isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {
69 return typeof (value as Promise<T>).then === 'function'
70}
71β
72function getSetCookieValues(headers: Headers): Array<string> {
73 const headersWithSetCookie = headers as HeadersWithGetSetCookie
74 if (typeof headersWithSetCookie.getSetCookie === 'function') {
75 return headersWithSetCookie.getSetCookie()
76 }
77 const value = headers.get('set-cookie')
78 return value ? [value] : []
79}
80β
81function mergeEventResponseHeaders(response: Response, event: H3Event): void {
82 if (response.ok) {
83 return
84 }
85β
86 const eventSetCookies = getSetCookieValues(event.res.headers)
87 if (eventSetCookies.length === 0) {
88 return
89 }
90β
91 const responseSetCookies = getSetCookieValues(response.headers)
92 response.headers.delete('set-cookie')
93 for (const cookie of responseSetCookies) {
94 response.headers.append('set-cookie', cookie)
95 }
96 for (const cookie of eventSetCookies) {
97 response.headers.append('set-cookie', cookie)
98 }
99}
100β
101function attachResponseHeaders<T>(
102 value: MaybePromise<T>,
103 event: H3Event,
104): MaybePromise<T> {
105 if (isPromiseLike(value)) {
106 return value.then((resolved) => {
107 if (resolved instanceof Response) {
108 mergeEventResponseHeaders(resolved, event)
109 }
110 return resolved
111 })
112 }
113β
114 if (value instanceof Response) {
115 mergeEventResponseHeaders(value, event)
116 }
117β
118 return value
119}
120β
121export function requestHandler<TRegister = unknown>(
122 handler: RequestHandler<TRegister>,
123) {
124 return (request: Request, requestOpts: any): Promise<Response> | Response => {
125 let h3Event: H3Event
126 try {
127 h3Event = new H3Event(request)
128 } catch (error) {
129 if (error instanceof URIError) {
130 return new Response(null, {
131 status: 400,
132 statusText: 'Bad Request',
133 })
134 }
135 throw error
136 }
137β
138 const response = eventStorage.run({ h3Event }, () =>
139 handler(request, requestOpts),
140 )
141 return h3_toResponse(attachResponseHeaders(response, h3Event), h3Event)
142 }
143}
144β
145function getH3Event() {
146 const event = eventStorage.getStore()
147 if (!event) {
148 throw new Error(
149 `No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,
150 )
151 }
152 return event.h3Event
153}
154β
155export function getRequest(): Request {
156 const event = getH3Event()
157 return event.req
158}
159β
160export function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {
161 return getH3Event().req.headers
162}
163β
164export function getRequestHeader(name: RequestHeaderName): string | undefined {
165 return getRequestHeaders().get(name) || undefined
166}
167β
168export function getRequestIP(opts?: {
169 /**
170 * Use the X-Forwarded-For HTTP header set by proxies.
171 *
172 * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.
173 */
174 xForwardedFor?: boolean
175}) {
176 return h3_getRequestIP(getH3Event(), opts)
177}
178β
179/**
180 * Get the request hostname.
181 *
182 * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
183 *
184 * If no host header is found, it will default to "localhost".
185 */
186export function getRequestHost(opts?: { xForwardedHost?: boolean }) {
187 return h3_getRequestHost(getH3Event(), opts)
188}
189β
190/**
191 * Get the full incoming request URL.
192 *
193 * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
194 *
195 * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.
196 */
197export function getRequestUrl(opts?: {
198 xForwardedHost?: boolean
199 xForwardedProto?: boolean
200}) {
201 return h3_getRequestURL(getH3Event(), opts)
202}
203β
204/**
205 * Get the request protocol.
206 *
207 * If `x-forwarded-proto` header is set to "https", it will return "https". You can disable this behavior by setting `xForwardedProto` to `false`.
208 *
209 * If protocol cannot be determined, it will default to "http".
210 */
211export function getRequestProtocol(opts?: {
212 xForwardedProto?: boolean
213}): 'http' | 'https' | (string & {}) {
214 return h3_getRequestProtocol(getH3Event(), opts)
215}
216β
217export function setResponseHeaders(
218 headers: TypedHeaders<ResponseHeaderMap>,
219): void {
220 const event = getH3Event()
221 if (event.res.headers === headers) {
222 return
223 }
224 let previousName = ''
225 // Headers iteration groups entries by name, including separate Set-Cookie values.
226 for (const [name, value] of headers) {
227 event.res.headers[name === previousName ? 'append' : 'set'](name, value)
228 previousName = name
229 }
230}
231β
232export function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {
233 const event = getH3Event()
234 return event.res.headers
235}
236β
237export function getResponseHeader(
238 name: ResponseHeaderName,
239): string | undefined {
240 const event = getH3Event()
241 return event.res.headers.get(name) || undefined
242}
243β
244export function setResponseHeader(
245 name: ResponseHeaderName,
246 value: string | Array<string>,
247): void {
248 const event = getH3Event()
249 if (Array.isArray(value)) {
250 event.res.headers.delete(name)
251 for (const valueItem of value) {
252 event.res.headers.append(name, valueItem)
253 }
254 } else {
255 event.res.headers.set(name, value)
256 }
257}
258export function removeResponseHeader(name: ResponseHeaderName): void {
259 const event = getH3Event()
260 event.res.headers.delete(name)
261}
262β
263export function clearResponseHeaders(
264 headerNames?: Array<ResponseHeaderName>,
265): void {
266 const event = getH3Event()
267 // If headerNames is provided, clear only those headers
268 if (headerNames && headerNames.length > 0) {
269 for (const name of headerNames) {
270 event.res.headers.delete(name)
271 }
272 // Otherwise, clear all headers
273 } else {
274 for (const name of event.res.headers.keys()) {
275 event.res.headers.delete(name)
276 }
277 }
278}
279β
280export function getResponseStatus(): number {
281 return getH3Event().res.status || 200
282}
283β
284export function setResponseStatus(code?: number, text?: string): void {
285 const event = getH3Event()
286 if (code) {
287 event.res.status = h3_sanitizeStatusCode(code, event.res.status)
288 }
289 if (text) {
290 event.res.statusText = h3_sanitizeStatusMessage(text)
291 }
292}
293β
294/**
295 * Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.
296 * @returns Object of cookie name-value pairs
297 * ```ts
298 * const cookies = getCookies()
299 * ```
300 */
301export function getCookies(): Record<string, string> {
302 const event = getH3Event()
303 const cookies = h3_parseCookies(event)
304 const definedCookies: Record<string, string> = Object.create(null)
305β
306 for (const [name, value] of Object.entries(cookies)) {
307 if (value !== undefined) {
308 definedCookies[name] = value
309 }
310 }
311β
312 return definedCookies
313}
314β
315/**
316 * Get a cookie value by name.
317 * @param name Name of the cookie to get
318 * @returns {*} Value of the cookie (String or undefined)
319 * ```ts
320 * const authorization = getCookie('Authorization')
321 * ```
322 */
323export function getCookie(name: string): string | undefined {
324 return getCookies()[name]
325}
326β
327/**
328 * Set a cookie value by name.
329 * @param name Name of the cookie to set
330 * @param value Value of the cookie to set
331 * @param options {CookieSerializeOptions} Options for serializing the cookie
332 * ```ts
333 * setCookie('Authorization', '1234567')
334 * ```
335 */
336export function setCookie(
337 name: string,
338 value: string,
339 options?: CookieSerializeOptions,
340): void {
341 const event = getH3Event()
342 h3_setCookie(event, name, value, options)
343}
344β
345/**
346 * Remove a cookie by name.
347 * @param name Name of the cookie to delete
348 * @param serializeOptions {CookieSerializeOptions} Cookie options
349 * ```ts
350 * deleteCookie('SessionId')
351 * ```
352 */
353export function deleteCookie(
354 name: string,
355 options?: CookieSerializeOptions,
356): void {
357 const event = getH3Event()
358 h3_deleteCookie(event, name, options)
359}
360β
361function getDefaultSessionConfig(config: SessionConfig): SessionConfig {
362 return {
363 name: 'start',
364 ...config,
365 }
366}
367β
368/**
369 * Create a session manager for the current request.
370 */
371export function useSession<TSessionData extends SessionData = SessionData>(
372 config: SessionConfig,
373): Promise<SessionManager<TSessionData>> {
374 const event = getH3Event()
375 return h3_useSession(event, getDefaultSessionConfig(config))
376}
377/**
378 * Get the session for the current request
379 */
380export function getSession<TSessionData extends SessionData = SessionData>(
381 config: SessionConfig,
382): Promise<Session<TSessionData>> {
383 const event = getH3Event()
384 return h3_getSession(event, getDefaultSessionConfig(config))
385}
386β
387/**
388 * Update the session data for the current request.
389 */
390export function updateSession<TSessionData extends SessionData = SessionData>(
391 config: SessionConfig,
392 update?: SessionUpdate<TSessionData>,
393): Promise<Session<TSessionData>> {
394 const event = getH3Event()
395 return h3_updateSession(event, getDefaultSessionConfig(config), update)
396}
397β
398/**
399 * Encrypt and sign the session data for the current request.
400 */
401export function sealSession(config: SessionConfig): Promise<string> {
402 const event = getH3Event()
403 return h3_sealSession(event, getDefaultSessionConfig(config))
404}
405/**
406 * Decrypt and verify the session data for the current request.
407 */
408export function unsealSession(
409 config: SessionConfig,
410 sealed: string,
411): Promise<Partial<Session>> {
412 const event = getH3Event()
413 return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)
414}
415β
416/**
417 * Clear the session data for the current request.
418 */
419export function clearSession(config: Partial<SessionConfig>): Promise<void> {
420 const event = getH3Event()
421 return h3_clearSession(event, { name: 'start', ...config })
422}
423β
424export function getResponse() {
425 const event = getH3Event()
426 return event.res
427}
428β
429// not public API (yet)
430export function getValidatedQuery<TSchema extends StandardSchemaV1>(
431 schema: StandardSchemaV1,
432): Promise<StandardSchemaV1.InferOutput<TSchema>> {
433 return h3_getValidatedQuery(getH3Event(), schema)
434}