Skip to content

Commit

Permalink
feat(miniapp-utils): DOMA-10738 support prepareSSRContext inside getI…
Browse files Browse the repository at this point in the history
…nitialProps (#5538)
  • Loading branch information
SavelevMatthew authored Nov 25, 2024
1 parent 7463c98 commit 2015628
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions packages/miniapp-utils/src/helpers/apollo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parse as parseCookieString, serialize as serializeCookie } from 'cookie'
import { setCookie } from 'cookies-next'
import { setCookie, getCookies } from 'cookies-next'

import {
FINGERPRINT_ID_COOKIE_NAME,
Expand All @@ -11,11 +11,6 @@ import { generateUUIDv4 } from './uuid'
import type { DefaultContext, RequestHandler } from '@apollo/client'
import type { IncomingMessage, ServerResponse } from 'http'


type RequestWithCookies = IncomingMessage & {
cookies: Partial<Record<string, string>>
}

type Response = ServerResponse

type SSRContext = {
Expand Down Expand Up @@ -85,19 +80,23 @@ export function getTracingMiddleware (options: TracingMiddlewareOptions): Reques
}
}

export function prepareSSRContext (req: RequestWithCookies, res: Response): SSRContext {
const requestCookies = {
...req.cookies,
export function prepareSSRContext (req?: IncomingMessage, res?: Response): SSRContext {
if (!req) {
return {
headers: {},
}
}

const requestCookies = getCookies({ req, res })

if (!requestCookies[FINGERPRINT_ID_COOKIE_NAME]) {
const fingerprint = generateFingerprint()
requestCookies[FINGERPRINT_ID_COOKIE_NAME] = fingerprint
// NOTE: req and res are used to operate "set-cookie" headers
setCookie(FINGERPRINT_ID_COOKIE_NAME, fingerprint, { req, res })
}

const cookieHeader = Object.entries(req.cookies)
const cookieHeader = Object.entries(requestCookies)
.map(([name, value]) => value ? serializeCookie(name, value) : null)
.filter(Boolean)
.join(';')
Expand Down

0 comments on commit 2015628

Please sign in to comment.