Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove setLazyProp from the hot path of all requests #55391

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/next/src/server/api-utils/get-cookie-parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { NextApiRequestCookies } from '.'

/**
* Parse cookies from the `headers` of request
* @param req request object
*/

export function getCookieParser(headers: {
[key: string]: string | string[] | null | undefined
}): () => NextApiRequestCookies {
return function parseCookie(): NextApiRequestCookies {
const { cookie } = headers

if (!cookie) {
return {}
}

const { parse: parseCookieFn } = require('next/dist/compiled/cookie')
return parseCookieFn(Array.isArray(cookie) ? cookie.join('; ') : cookie)
}
}
19 changes: 0 additions & 19 deletions packages/next/src/server/api-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,6 @@ export type __ApiPreviewProps = {
previewModeSigningKey: string
}

/**
* Parse cookies from the `headers` of request
* @param req request object
*/
export function getCookieParser(headers: {
[key: string]: string | string[] | null | undefined
}): () => NextApiRequestCookies {
return function parseCookie(): NextApiRequestCookies {
const { cookie } = headers

if (!cookie) {
return {}
}

const { parse: parseCookieFn } = require('next/dist/compiled/cookie')
return parseCookieFn(Array.isArray(cookie) ? cookie.join('; ') : cookie)
}
}

/**
*
* @param res response object
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/server/api-utils/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import isError from '../../lib/is-error'
import { isResSent } from '../../shared/lib/utils'
import { interopDefault } from '../../lib/interop-default'
import {
getCookieParser,
setLazyProp,
sendStatusCode,
redirect,
Expand All @@ -27,6 +26,7 @@ import {
SYMBOL_PREVIEW_DATA,
RESPONSE_LIMIT_DEFAULT,
} from './index'
import { getCookieParser } from './get-cookie-parser'
import { getTracer } from '../lib/trace/tracer'
import { NodeSpan } from '../lib/trace/constants'
import { RequestCookies } from '../web/spec-extension/cookies'
Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/server/base-http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'
import type { I18NConfig } from '../config-shared'

import { PERMANENT_REDIRECT_STATUS } from '../../shared/lib/constants'
import { getCookieParser, NextApiRequestCookies } from '../api-utils'
import { NextApiRequestCookies } from '../api-utils'
import { getCookieParser } from '../api-utils/get-cookie-parser'

export interface BaseNextRequestConfig {
basePath: string | undefined
Expand Down
8 changes: 1 addition & 7 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,7 @@ import {
TEMPORARY_REDIRECT_STATUS,
} from '../shared/lib/constants'
import { isDynamicRoute } from '../shared/lib/router/utils'
import {
setLazyProp,
getCookieParser,
checkIsOnDemandRevalidate,
} from './api-utils'
import { checkIsOnDemandRevalidate } from './api-utils'
import { setConfig } from '../shared/lib/runtime-config.shared-runtime'

import { setRevalidateHeaders } from './send-payload/revalidate-headers'
Expand Down Expand Up @@ -791,8 +787,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return
}

setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))

// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
parsedUrl = parseUrl(req.url!, true)
Expand Down
2 changes: 0 additions & 2 deletions packages/next/src/server/lib/router-utils/resolve-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { stringifyQuery } from '../../server-route-utils'
import { formatHostname } from '../format-hostname'
import { toNodeOutgoingHttpHeaders } from '../../web/utils'
import { isAbortError } from '../../pipe-readable'
import { getCookieParser, setLazyProp } from '../../api-utils'
import { getHostname } from '../../../shared/lib/get-hostname'
import { UnwrapPromise } from '../../../lib/coalesced-function'
import { getRedirectStatus } from '../../../lib/redirect-status'
Expand Down Expand Up @@ -154,7 +153,6 @@ export function getResolveRoutes(
addRequestMeta(req, '__NEXT_INIT_URL', initUrl)
addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query })
addRequestMeta(req, '_protocol', protocol)
setLazyProp({ req }, 'cookies', () => getCookieParser(req.headers)())

if (!isUpgradeReq) {
addRequestMeta(req, '__NEXT_CLONABLE_BODY', getCloneableBody(req))
Expand Down
10 changes: 9 additions & 1 deletion packages/next/src/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import type {
} from '../shared/lib/utils'
import type { ImageConfigComplete } from '../shared/lib/image-config'
import type { Redirect } from '../lib/load-custom-routes'
import type { NextApiRequestCookies, __ApiPreviewProps } from './api-utils'
import {
type NextApiRequestCookies,
type __ApiPreviewProps,
setLazyProp,
} from './api-utils'
import { getCookieParser } from './api-utils/get-cookie-parser'
import type { FontManifest, FontConfig } from './font-utils'
import type { LoadComponentsReturnType, ManifestItem } from './load-components'
import type {
Expand Down Expand Up @@ -386,6 +391,9 @@ export async function renderToHTMLImpl(
renderOpts: Omit<RenderOpts, keyof RenderOptsExtra>,
extra: RenderOptsExtra
): Promise<RenderResult> {
// Adds support for reading `cookies` in `getServerSideProps` when SSR.
setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))

const renderResultMeta: RenderResultMetadata = {}

// In dev we invalidate the cache by appending a timestamp to the resource URL.
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/shared/lib/i18n/get-locale-redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { acceptLanguage } from '../../../server/accept-header'
import { denormalizePagePath } from '../page-path/denormalize-page-path'
import { detectDomainLocale } from './detect-domain-locale'
import { formatUrl } from '../router/utils/format-url'
import { getCookieParser } from '../../../server/api-utils'
import { getCookieParser } from '../../../server/api-utils/get-cookie-parser'

interface Options {
defaultLocale: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
isInterceptionRouteAppPath,
} from '../../../../server/future/helpers/interception-routes'
import { NEXT_RSC_UNION_QUERY } from '../../../../client/components/app-router-headers'
import { getCookieParser } from '../../../../server/api-utils/get-cookie-parser'

/**
* Ensure only a-zA-Z are used for param names for proper interpolating
Expand Down Expand Up @@ -64,7 +65,13 @@ export function matchHas(
break
}
case 'cookie': {
value = (req as any).cookies[hasItem.key]
if ('cookies' in req) {
value = req.cookies[hasItem.key]
} else {
const cookies = getCookieParser(req.headers)()
value = cookies[hasItem.key]
}

break
}
case 'query': {
Expand Down
17 changes: 15 additions & 2 deletions test/integration/typescript/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ const handleOutput = (msg) => {
output += msg
}

async function get$(path, query) {
const html = await renderViaHTTP(appPort, path, query)
async function get$(path, query, options) {
const html = await renderViaHTTP(appPort, path, query, options)
return cheerio.load(html)
}

Expand All @@ -49,6 +49,19 @@ describe('TypeScript Features', () => {
expect($('#cookies').text()).toBe('{}')
})

it('should render the cookies page with cookies', async () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was no test for req.cookies values in getServerSideProps but that is supported today so added a test for it to ensure it doesn't break in the future (and that this change is correct).

const $ = await get$(
'/ssr/cookies',
{},
{
headers: {
Cookie: 'key=value;',
},
}
)
expect($('#cookies').text()).toBe(`{"key":"value"}`)
})

it('should render the generics page', async () => {
const $ = await get$('/generics')
expect($('#value').text()).toBe('Hello World from Generic')
Expand Down