Unverified Commit 1fbbba6f authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Unify Request types (#47884)

This serves to start the transition of replacing the following:

- Replace `BaseNextRequest`, `WebNextRequest`, and `NodeNextRequest`
with `NextRequest`
- Replace `BaseNextResponse`, `WebNextResponse`, and `NodeNextResponse`
with `Response`

This will currently only apply to app routes, enabling the following:

```ts
////////////////////////////////////////////////////////////////////////////////
// Use `Request` and `Response`
////////////////////////////////////////////////////////////////////////////////

import { NextRequest, NextResponse } from 'next/server'

export function GET(request: Request): Response {
  return new Response(
    JSON.stringify({
      hello: request.headers.get('user-agent'),
    }),
    { headers: { 'content-type': 'application/json' } }
  )
}

////////////////////////////////////////////////////////////////////////////////
// Use `NextRequest` and `NextResponse`
////////////////////////////////////////////////////////////////////////////////

import { NextRequest, NextResponse } from 'next/server'

export function GET(request: NextRequest): NextResponse {
  return NextResponse.json({ hello: request.headers.get('user-agent') })
}

////////////////////////////////////////////////////////////////////////////////
// Use `NextRequest` and `Response`
////////////////////////////////////////////////////////////////////////////////

import { NextRequest, NextResponse } from 'next/server'

// `NextRequest` extends `Request`.
export function GET(request: NextRequest): Response {
  return new Response(
    JSON.stringify({ hello: request.headers.get('user-agent') }),
    { headers: { 'content-type': 'application/json' } }
  )
}

////////////////////////////////////////////////////////////////////////////////
// Use `NextRequest`, `NextResponse`, and `Response`
////////////////////////////////////////////////////////////////////////////////

import { NextRequest, NextResponse } from 'next/server'

export function GET(request: NextRequest): Response {
  // `NextResponse` extends `Response`.
  return NextResponse.json({ hello: request.headers.get('user-agent') })
}

////////////////////////////////////////////////////////////////////////////////
// Use `Request` and `NextResponse`
////////////////////////////////////////////////////////////////////////////////

import { NextRequest, NextResponse } from 'next/server'

export function GET(request: Request): NextResponse {
  return NextResponse.json({ hello: request.headers.get('user-agent') })
}

```

fix NEXT-713
parent 2c9b484f
// PAGE and PATHNAME is set from rust code // PAGE and PATHNAME is set from rust code
declare const PAGE: string, PATHNAME: string; declare const PAGE: string, PATHNAME: string;
import { EdgeModuleWrapper } from "next/dist/build/webpack/loaders/next-edge-app-route-loader/edge-module-wrapper"; import { EdgeRouteModuleWrapper } from "next/dist/server/web/edge-route-module-wrapper";
import RouteModule from "ROUTE_MODULE"; import RouteModule from "ROUTE_MODULE";
import * as userland from "ENTRY"; import * as userland from "ENTRY";
...@@ -17,6 +17,6 @@ const routeModule = new RouteModule({ ...@@ -17,6 +17,6 @@ const routeModule = new RouteModule({
// @ts-expect-error - exposed for edge support // @ts-expect-error - exposed for edge support
globalThis._ENTRIES = { globalThis._ENTRIES = {
middleware_edge: { middleware_edge: {
default: EdgeModuleWrapper.wrap(routeModule, { page: `/${PAGE}` }), default: EdgeRouteModuleWrapper.wrap(routeModule, { page: `/${PAGE}` }),
}, },
}; };
...@@ -42,12 +42,12 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -42,12 +42,12 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
)}?__edge_ssr_entry__` )}?__edge_ssr_entry__`
return ` return `
import { EdgeModuleWrapper } from 'next/dist/esm/build/webpack/loaders/next-edge-app-route-loader/edge-module-wrapper' import { EdgeRouteModuleWrapper } from 'next/dist/esm/server/web/edge-route-module-wrapper'
import * as module from ${JSON.stringify(modulePath)} import * as module from ${JSON.stringify(modulePath)}
export const ComponentMod = module export const ComponentMod = module
export default EdgeModuleWrapper.wrap(module.routeModule)` export default EdgeRouteModuleWrapper.wrap(module.routeModule)`
} }
export default EdgeAppRouteLoader export default EdgeAppRouteLoader
import { RequestCookiesAdapter } from '../../server/web/spec-extension/adapters/request-cookies'
import { HeadersAdapter } from '../../server/web/spec-extension/adapters/headers'
import { RequestCookies } from '../../server/web/spec-extension/cookies' import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { requestAsyncStorage } from './request-async-storage' import { requestAsyncStorage } from './request-async-storage'
import { staticGenerationBailout } from './static-generation-bailout' import { staticGenerationBailout } from './static-generation-bailout'
export function headers() { export function headers() {
if (staticGenerationBailout('headers')) { if (staticGenerationBailout('headers')) {
return new Headers({}) return HeadersAdapter.seal(new Headers({}))
} }
const requestStore = requestAsyncStorage.getStore() const requestStore = requestAsyncStorage.getStore()
...@@ -30,7 +32,7 @@ export function previewData() { ...@@ -30,7 +32,7 @@ export function previewData() {
export function cookies() { export function cookies() {
if (staticGenerationBailout('cookies')) { if (staticGenerationBailout('cookies')) {
return new RequestCookies(new Headers({})) return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))
} }
const requestStore = requestAsyncStorage.getStore() const requestStore = requestAsyncStorage.getStore()
......
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import { PreviewData } from '../../../types' import type { PreviewData } from '../../../types'
import type { ReadonlyHeaders } from '../../server/app-render/readonly-headers' import type { ReadonlyHeaders } from '../../server/web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../../server/app-render/readonly-request-cookies' import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/adapters/request-cookies'
import { createAsyncLocalStorage } from './async-local-storage' import { createAsyncLocalStorage } from './async-local-storage'
export interface RequestStore { export interface RequestStore {
......
...@@ -47,11 +47,12 @@ import { IncrementalCache } from '../server/lib/incremental-cache' ...@@ -47,11 +47,12 @@ import { IncrementalCache } from '../server/lib/incremental-cache'
import { isNotFoundError } from '../client/components/not-found' import { isNotFoundError } from '../client/components/not-found'
import { isRedirectError } from '../client/components/redirect' import { isRedirectError } from '../client/components/redirect'
import { NEXT_DYNAMIC_NO_SSR_CODE } from '../shared/lib/lazy-dynamic/no-ssr-error' import { NEXT_DYNAMIC_NO_SSR_CODE } from '../shared/lib/lazy-dynamic/no-ssr-error'
import { mockRequest } from '../server/lib/mock-request' import { createRequestResponseMocks } from '../server/lib/mock-request'
import { NodeNextRequest } from '../server/base-http/node' import { NodeNextRequest } from '../server/base-http/node'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { toNodeHeaders } from '../server/web/utils' import { toNodeHeaders } from '../server/web/utils'
import { RouteModuleLoader } from '../server/future/helpers/module-loader/route-module-loader' import { RouteModuleLoader } from '../server/future/helpers/module-loader/route-module-loader'
import { NextRequestAdapter } from '../server/web/spec-extension/adapters/next-request'
loadRequireHook() loadRequireHook()
...@@ -236,7 +237,7 @@ export default async function exportPage({ ...@@ -236,7 +237,7 @@ export default async function exportPage({
} }
} }
const { req, res } = mockRequest(updatedPath, {}, 'GET') const { req, res } = createRequestResponseMocks({ url: updatedPath })
for (const statusCode of [404, 500]) { for (const statusCode of [404, 500]) {
if ( if (
...@@ -385,12 +386,10 @@ export default async function exportPage({ ...@@ -385,12 +386,10 @@ export default async function exportPage({
isRedirectError(err) isRedirectError(err)
if (isRouteHandler) { if (isRouteHandler) {
const request = new NodeNextRequest(req) // Ensure that the url for the page is absolute.
req.url = `http://localhost:3000${req.url}`
addRequestMeta( const request = NextRequestAdapter.fromNodeNextRequest(
request.originalRequest, new NodeNextRequest(req)
'__NEXT_INIT_URL',
`http://localhost:3000${req.url}`
) )
// Create the context for the handler. This contains the params from // Create the context for the handler. This contains the params from
......
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import type { BaseNextRequest } from '../base-http' import type { BaseNextRequest } from '../base-http'
import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils'
import type { CookieSerializeOptions } from 'next/dist/compiled/cookie' import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
export type NextApiRequestCookies = Partial<{ [key: string]: string }> export type NextApiRequestCookies = Partial<{ [key: string]: string }>
export type NextApiRequestQuery = Partial<{ [key: string]: string | string[] }> export type NextApiRequestQuery = Partial<{ [key: string]: string | string[] }>
...@@ -18,17 +19,17 @@ export type __ApiPreviewProps = { ...@@ -18,17 +19,17 @@ export type __ApiPreviewProps = {
* @param req request object * @param req request object
*/ */
export function getCookieParser(headers: { export function getCookieParser(headers: {
[key: string]: undefined | string | string[] [key: string]: string | string[] | null | undefined
}): () => NextApiRequestCookies { }): () => NextApiRequestCookies {
return function parseCookie(): NextApiRequestCookies { return function parseCookie(): NextApiRequestCookies {
const header: undefined | string | string[] = headers.cookie const { cookie } = headers
if (!header) { if (!cookie) {
return {} return {}
} }
const { parse: parseCookieFn } = require('next/dist/compiled/cookie') const { parse: parseCookieFn } = require('next/dist/compiled/cookie')
return parseCookieFn(Array.isArray(header) ? header.join(';') : header) return parseCookieFn(Array.isArray(cookie) ? cookie.join('; ') : cookie)
} }
} }
...@@ -76,18 +77,22 @@ export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = ...@@ -76,18 +77,22 @@ export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
'x-prerender-revalidate-if-generated' 'x-prerender-revalidate-if-generated'
export function checkIsOnDemandRevalidate( export function checkIsOnDemandRevalidate(
req: IncomingMessage | BaseNextRequest, req: Request | IncomingMessage | BaseNextRequest,
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
): { ): {
isOnDemandRevalidate: boolean isOnDemandRevalidate: boolean
revalidateOnlyGenerated: boolean revalidateOnlyGenerated: boolean
} { } {
return { const headers = HeadersAdapter.from(req.headers)
isOnDemandRevalidate:
req.headers[PRERENDER_REVALIDATE_HEADER] === previewProps.previewModeId, const previewModeId = headers.get(PRERENDER_REVALIDATE_HEADER)
revalidateOnlyGenerated: const isOnDemandRevalidate = previewModeId === previewProps.previewModeId
!!req.headers[PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER],
} const revalidateOnlyGenerated = headers.has(
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER
)
return { isOnDemandRevalidate, revalidateOnlyGenerated }
} }
export const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass` export const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
......
...@@ -26,19 +26,20 @@ import { ...@@ -26,19 +26,20 @@ import {
clearPreviewData, clearPreviewData,
sendError, sendError,
ApiError, ApiError,
NextApiRequestCookies,
PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_HEADER,
COOKIE_NAME_PRERENDER_BYPASS, COOKIE_NAME_PRERENDER_BYPASS,
COOKIE_NAME_PRERENDER_DATA, COOKIE_NAME_PRERENDER_DATA,
SYMBOL_PREVIEW_DATA, SYMBOL_PREVIEW_DATA,
RESPONSE_LIMIT_DEFAULT, RESPONSE_LIMIT_DEFAULT,
} from './index' } from './index'
import { mockRequest } from '../lib/mock-request' import { createRequestResponseMocks } from '../lib/mock-request'
import { getTracer } from '../lib/trace/tracer' import { getTracer } from '../lib/trace/tracer'
import { NodeSpan } from '../lib/trace/constants' import { NodeSpan } from '../lib/trace/constants'
import { RequestCookies } from '../web/spec-extension/cookies'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
export function tryGetPreviewData( export function tryGetPreviewData(
req: IncomingMessage | BaseNextRequest, req: IncomingMessage | BaseNextRequest | Request,
res: ServerResponse | BaseNextResponse, res: ServerResponse | BaseNextResponse,
options: __ApiPreviewProps options: __ApiPreviewProps
): PreviewData { ): PreviewData {
...@@ -49,41 +50,34 @@ export function tryGetPreviewData( ...@@ -49,41 +50,34 @@ export function tryGetPreviewData(
} }
// Read cached preview data if present // Read cached preview data if present
// TODO: use request metadata instead of a symbol
if (SYMBOL_PREVIEW_DATA in req) { if (SYMBOL_PREVIEW_DATA in req) {
return (req as any)[SYMBOL_PREVIEW_DATA] as any return (req as any)[SYMBOL_PREVIEW_DATA] as any
} }
const getCookies = getCookieParser(req.headers) const headers = HeadersAdapter.from(req.headers)
let cookies: NextApiRequestCookies const cookies = new RequestCookies(headers)
try {
cookies = getCookies()
} catch {
// TODO: warn
return false
}
const hasBypass = COOKIE_NAME_PRERENDER_BYPASS in cookies const previewModeId = cookies.get(COOKIE_NAME_PRERENDER_BYPASS)?.value
const hasData = COOKIE_NAME_PRERENDER_DATA in cookies const tokenPreviewData = cookies.get(COOKIE_NAME_PRERENDER_DATA)?.value
// Case: neither cookie is set. // Case: neither cookie is set.
if (!(hasBypass || hasData)) { if (!previewModeId && !tokenPreviewData) {
return false return false
} }
// Case: one cookie is set, but not the other. // Case: one cookie is set, but not the other.
if (hasBypass !== hasData) { if (!previewModeId || !tokenPreviewData) {
clearPreviewData(res as NextApiResponse) clearPreviewData(res as NextApiResponse)
return false return false
} }
// Case: preview session is for an old build. // Case: preview session is for an old build.
if (cookies[COOKIE_NAME_PRERENDER_BYPASS] !== options.previewModeId) { if (previewModeId !== options.previewModeId) {
clearPreviewData(res as NextApiResponse) clearPreviewData(res as NextApiResponse)
return false return false
} }
const tokenPreviewData = cookies[COOKIE_NAME_PRERENDER_DATA] as string
let encryptedPreviewData: { let encryptedPreviewData: {
data: string data: string
} }
...@@ -409,19 +403,19 @@ async function revalidate( ...@@ -409,19 +403,19 @@ async function revalidate(
throw new Error(`Invalid response ${res.status}`) throw new Error(`Invalid response ${res.status}`)
} }
} else if (context.revalidate) { } else if (context.revalidate) {
const { const mocked = createRequestResponseMocks({
req: mockReq, url: urlPath,
res: mockRes, headers: revalidateHeaders,
streamPromise, })
} = mockRequest(urlPath, revalidateHeaders, 'GET')
await context.revalidate(mockReq, mockRes) await context.revalidate(mocked.req, mocked.res)
await streamPromise await mocked.res.hasStreamed
if ( if (
mockRes.getHeader('x-nextjs-cache') !== 'REVALIDATED' && mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&
!(mockRes.statusCode === 404 && opts.unstable_onlyGenerated) !(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)
) { ) {
throw new Error(`Invalid response ${mockRes.statusCode}`) throw new Error(`Invalid response ${mocked.res.statusCode}`)
} }
} else { } else {
throw new Error( throw new Error(
......
import type { IncomingHttpHeaders } from 'http'
const INTERNAL_HEADERS_INSTANCE = Symbol('internal for headers readonly')
function readonlyHeadersError() {
return new Error('ReadonlyHeaders cannot be modified')
}
export class ReadonlyHeaders {
[INTERNAL_HEADERS_INSTANCE]: Headers
entries: Headers['entries']
forEach: Headers['forEach']
get: Headers['get']
has: Headers['has']
keys: Headers['keys']
values: Headers['values']
constructor(headers: IncomingHttpHeaders) {
// Since `new Headers` uses `this.append()` to fill the headers object ReadonlyHeaders can't extend from Headers directly as it would throw.
const headersInstance = new Headers(headers as any)
this[INTERNAL_HEADERS_INSTANCE] = headersInstance
this.entries = headersInstance.entries.bind(headersInstance)
this.forEach = headersInstance.forEach.bind(headersInstance)
this.get = headersInstance.get.bind(headersInstance)
this.has = headersInstance.has.bind(headersInstance)
this.keys = headersInstance.keys.bind(headersInstance)
this.values = headersInstance.values.bind(headersInstance)
}
[Symbol.iterator]() {
return this[INTERNAL_HEADERS_INSTANCE][Symbol.iterator]()
}
append() {
throw readonlyHeadersError()
}
delete() {
throw readonlyHeadersError()
}
set() {
throw readonlyHeadersError()
}
}
import { RequestCookies } from '../web/spec-extension/cookies'
const INTERNAL_COOKIES_INSTANCE = Symbol('internal for cookies readonly')
class ReadonlyRequestCookiesError extends Error {
message =
'ReadonlyRequestCookies cannot be modified. Read more: https://nextjs.org/api-reference/cookies'
}
export class ReadonlyRequestCookies {
[INTERNAL_COOKIES_INSTANCE]: RequestCookies
get: RequestCookies['get']
getAll: RequestCookies['getAll']
has: RequestCookies['has']
constructor(request: {
headers: {
get(key: 'cookie'): string | null | undefined
}
}) {
// Since `new Headers` uses `this.append()` to fill the headers object ReadonlyHeaders can't extend from Headers directly as it would throw.
// Request overridden to not have to provide a fully request object.
const cookiesInstance = new RequestCookies(request.headers as Headers)
this[INTERNAL_COOKIES_INSTANCE] = cookiesInstance
this.get = cookiesInstance.get.bind(cookiesInstance)
this.getAll = cookiesInstance.getAll.bind(cookiesInstance)
this.has = cookiesInstance.has.bind(cookiesInstance)
}
[Symbol.iterator]() {
return (this[INTERNAL_COOKIES_INSTANCE] as any)[Symbol.iterator]()
}
clear() {
throw new ReadonlyRequestCookiesError()
}
delete() {
throw new ReadonlyRequestCookiesError()
}
set() {
throw new ReadonlyRequestCookiesError()
}
}
...@@ -6,17 +6,33 @@ import type { PreviewData } from '../../../types' ...@@ -6,17 +6,33 @@ import type { PreviewData } from '../../../types'
import type { RequestStore } from '../../client/components/request-async-storage' import type { RequestStore } from '../../client/components/request-async-storage'
import type { RenderOpts } from '../app-render/types' import type { RenderOpts } from '../app-render/types'
import type { AsyncStorageWrapper } from './async-storage-wrapper' import type { AsyncStorageWrapper } from './async-storage-wrapper'
import type { NextRequest } from '../web/spec-extension/request'
import { FLIGHT_PARAMETERS } from '../../client/components/app-router-headers' import { FLIGHT_PARAMETERS } from '../../client/components/app-router-headers'
import { ReadonlyHeaders } from '../app-render/readonly-headers' import {
import { ReadonlyRequestCookies } from '../app-render/readonly-request-cookies' HeadersAdapter,
type ReadonlyHeaders,
} from '../web/spec-extension/adapters/headers'
import {
RequestCookiesAdapter,
type ReadonlyRequestCookies,
} from '../web/spec-extension/adapters/request-cookies'
import { RequestCookies } from '../web/spec-extension/cookies'
function headersWithoutFlight(headers: IncomingHttpHeaders) { function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
const newHeaders = { ...headers } const cleaned = HeadersAdapter.from(headers)
for (const param of FLIGHT_PARAMETERS) { for (const param of FLIGHT_PARAMETERS) {
delete newHeaders[param.toString().toLowerCase()] cleaned.delete(param.toString().toLowerCase())
} }
return newHeaders
return HeadersAdapter.seal(cleaned)
}
function getCookies(
headers: Headers | IncomingHttpHeaders
): ReadonlyRequestCookies {
const cookies = new RequestCookies(HeadersAdapter.from(headers))
return RequestCookiesAdapter.seal(cookies)
} }
/** /**
...@@ -29,7 +45,7 @@ const tryGetPreviewData: typeof TryGetPreviewData | null = ...@@ -29,7 +45,7 @@ const tryGetPreviewData: typeof TryGetPreviewData | null =
: null : null
export type RequestContext = { export type RequestContext = {
req: IncomingMessage | BaseNextRequest req: IncomingMessage | BaseNextRequest | NextRequest
res?: ServerResponse | BaseNextResponse res?: ServerResponse | BaseNextResponse
renderOpts?: RenderOpts renderOpts?: RenderOpts
} }
...@@ -61,32 +77,29 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -61,32 +77,29 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
tryGetPreviewData(req, res, (renderOpts as any).previewProps) tryGetPreviewData(req, res, (renderOpts as any).previewProps)
: false : false
let cachedHeadersInstance: ReadonlyHeaders const cache: {
let cachedCookiesInstance: ReadonlyRequestCookies headers?: ReadonlyHeaders
cookies?: ReadonlyRequestCookies
} = {}
const store: RequestStore = { const store: RequestStore = {
get headers() { get headers() {
if (!cachedHeadersInstance) { if (!cache.headers) {
cachedHeadersInstance = new ReadonlyHeaders( // Seal the headers object that'll freeze out any methods that could
headersWithoutFlight(req.headers) // mutate the underlying data.
) cache.headers = getHeaders(req.headers)
} }
return cachedHeadersInstance
return cache.headers
}, },
get cookies() { get cookies() {
if (!cachedCookiesInstance) { if (!cache.cookies) {
cachedCookiesInstance = new ReadonlyRequestCookies({ // Seal the cookies object that'll freeze out any methods that could
headers: { // mutate the underlying data.
get: (key) => { cache.cookies = getCookies(req.headers)
if (key !== 'cookie') {
throw new Error('Only cookie header is supported')
} }
return req.headers.cookie
}, return cache.cookies
},
})
}
return cachedCookiesInstance
}, },
previewData, previewData,
} }
......
...@@ -6,6 +6,7 @@ import type { AppRouteRouteHandlerContext } from '../route-modules/app-route/mod ...@@ -6,6 +6,7 @@ import type { AppRouteRouteHandlerContext } from '../route-modules/app-route/mod
import { NodeModuleLoader } from '../helpers/module-loader/node-module-loader' import { NodeModuleLoader } from '../helpers/module-loader/node-module-loader'
import { RouteModuleLoader } from '../helpers/module-loader/route-module-loader' import { RouteModuleLoader } from '../helpers/module-loader/route-module-loader'
import { NextRequestAdapter } from '../../web/spec-extension/adapters/next-request'
/** /**
* RouteHandlerManager is a manager for route handlers. * RouteHandlerManager is a manager for route handlers.
...@@ -36,10 +37,10 @@ export class RouteHandlerManager { ...@@ -36,10 +37,10 @@ export class RouteHandlerManager {
// cache will be cleared and the module will be re-created. // cache will be cleared and the module will be re-created.
module.setup() module.setup()
// Get the response from the handler. // Convert the BaseNextRequest to a NextRequest.
const response = await module.handle(req, context) const request = NextRequestAdapter.fromBaseNextRequest(req)
// Send the response back. // Get the response from the handler and send it back.
return response return await module.handle(request, context)
} }
} }
...@@ -9,7 +9,7 @@ import { NextURL } from '../../../../web/next-url' ...@@ -9,7 +9,7 @@ import { NextURL } from '../../../../web/next-url'
import { cleanURL } from './clean-url' import { cleanURL } from './clean-url'
export function proxyRequest( export function proxyRequest(
req: NextRequest | Request, request: NextRequest,
{ dynamic }: Pick<AppRouteUserlandModule, 'dynamic'>, { dynamic }: Pick<AppRouteUserlandModule, 'dynamic'>,
hooks: { hooks: {
readonly serverHooks: typeof ServerHooks readonly serverHooks: typeof ServerHooks
...@@ -76,9 +76,7 @@ export function proxyRequest( ...@@ -76,9 +76,7 @@ export function proxyRequest(
} }
} }
const wrappedNextUrl = const wrappedNextUrl = new Proxy(request.nextUrl, {
'nextUrl' in req
? new Proxy(req.nextUrl, {
get(target, prop) { get(target, prop) {
handleNextUrlBailout(prop) handleNextUrlBailout(prop)
...@@ -99,7 +97,6 @@ export function proxyRequest( ...@@ -99,7 +97,6 @@ export function proxyRequest(
return true return true
}, },
}) })
: undefined
const handleReqBailout = (prop: string | symbol) => { const handleReqBailout = (prop: string | symbol) => {
switch (prop) { switch (prop) {
...@@ -123,7 +120,7 @@ export function proxyRequest( ...@@ -123,7 +120,7 @@ export function proxyRequest(
} }
} }
return new Proxy(req, { return new Proxy(request, {
get(target, prop) { get(target, prop) {
handleReqBailout(prop) handleReqBailout(prop)
......
import type { NodeNextRequest } from '../../../../base-http/node'
import type { BaseNextRequest } from '../../../../base-http'
import { getRequestMeta } from '../../../../request-meta'
import { NextRequest } from '../../../../web/spec-extension/request'
import { fromNodeHeaders } from '../../../../web/utils'
/**
* Wraps the base next request to a request compatible with the app route
* signature.
*
* @param req base request to adapt for use with app routes
* @returns the wrapped request.
*/
export function wrapRequest(req: BaseNextRequest): NextRequest {
const { originalRequest } = req as NodeNextRequest
const url = getRequestMeta(originalRequest, '__NEXT_INIT_URL')
if (!url) throw new Error('Invariant: missing url on request')
// HEAD and GET requests can not have a body.
const body: BodyInit | null | undefined =
req.method !== 'GET' && req.method !== 'HEAD' && req.body ? req.body : null
return new NextRequest(url, {
body,
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: 'half',
method: req.method,
headers: fromNodeHeaders(req.headers),
})
}
...@@ -2,9 +2,7 @@ import type { Params } from '../../../../shared/lib/router/utils/route-matcher' ...@@ -2,9 +2,7 @@ import type { Params } from '../../../../shared/lib/router/utils/route-matcher'
import type { NextConfig } from '../../../config-shared' import type { NextConfig } from '../../../config-shared'
import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition' import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition'
import type { AppConfig } from '../../../../build/utils' import type { AppConfig } from '../../../../build/utils'
import type { WebNextRequest } from '../../../base-http/web' import type { NextRequest } from '../../../web/spec-extension/request'
import type { NodeNextRequest } from '../../../base-http/node'
import type { BaseNextRequest } from '../../../base-http'
import { import {
RouteModule, RouteModule,
...@@ -23,14 +21,13 @@ import { ...@@ -23,14 +21,13 @@ import {
handleBadRequestResponse, handleBadRequestResponse,
handleInternalServerErrorResponse, handleInternalServerErrorResponse,
} from '../helpers/response-handlers' } from '../helpers/response-handlers'
import { HTTP_METHOD, HTTP_METHODS, isHTTPMethod } from '../../../web/http' import { type HTTP_METHOD, HTTP_METHODS, isHTTPMethod } from '../../../web/http'
import { patchFetch } from '../../../lib/patch-fetch' import { patchFetch } from '../../../lib/patch-fetch'
import { getTracer } from '../../../lib/trace/tracer' import { getTracer } from '../../../lib/trace/tracer'
import { AppRouteRouteHandlersSpan } from '../../../lib/trace/constants' import { AppRouteRouteHandlersSpan } from '../../../lib/trace/constants'
import { getPathnameFromAbsolutePath } from './helpers/get-pathname-from-absolute-path' import { getPathnameFromAbsolutePath } from './helpers/get-pathname-from-absolute-path'
import { proxyRequest } from './helpers/proxy-request' import { proxyRequest } from './helpers/proxy-request'
import { resolveHandlerError } from './helpers/resolve-handler-error' import { resolveHandlerError } from './helpers/resolve-handler-error'
import { wrapRequest } from './helpers/wrap-request'
import { RouteKind } from '../../route-kind' import { RouteKind } from '../../route-kind'
import * as Log from '../../../../build/output/log' import * as Log from '../../../../build/output/log'
import { autoImplementMethods } from './helpers/auto-implement-methods' import { autoImplementMethods } from './helpers/auto-implement-methods'
...@@ -231,18 +228,15 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -231,18 +228,15 @@ export class AppRouteRouteModule extends RouteModule<
* Executes the route handler. * Executes the route handler.
*/ */
private async execute( private async execute(
req: BaseNextRequest, request: NextRequest,
context: AppRouteRouteHandlerContext context: AppRouteRouteHandlerContext
): Promise<Response> { ): Promise<Response> {
// Get the handler function for the given method. // Get the handler function for the given method.
const handler = this.resolve(req.method) const handler = this.resolve(request.method)
// Get the context for the request. // Get the context for the request.
const requestContext: RequestContext = { const requestContext: RequestContext = {
req: req: request,
'request' in (req as WebNextRequest)
? req
: (req as NodeNextRequest).originalRequest,
} }
// Get the context for the static generation. // Get the context for the static generation.
...@@ -260,8 +254,9 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -260,8 +254,9 @@ export class AppRouteRouteModule extends RouteModule<
staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache
// Run the handler with the request AsyncLocalStorage to inject the helper // Run the handler with the request AsyncLocalStorage to inject the helper
// support. // support. We set this to `unknown` because the type is not known until
const response = await RequestAsyncStorageWrapper.wrap( // runtime when we do a instanceof check below.
const response: unknown = await RequestAsyncStorageWrapper.wrap(
this.requestAsyncStorage, this.requestAsyncStorage,
requestContext, requestContext,
() => () =>
...@@ -308,10 +303,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -308,10 +303,7 @@ export class AppRouteRouteModule extends RouteModule<
// Wrap the request so we can add additional functionality to cases // Wrap the request so we can add additional functionality to cases
// that might change it's output or affect the rendering. // that might change it's output or affect the rendering.
const wrappedRequest = proxyRequest( const wrappedRequest = proxyRequest(
// TODO: (wyattjoh) replace with unified request type request,
'request' in (req as WebNextRequest)
? ((req as WebNextRequest).request as Request)
: wrapRequest(req),
{ dynamic: this.dynamic }, { dynamic: this.dynamic },
{ {
headerHooks: this.headerHooks, headerHooks: this.headerHooks,
...@@ -384,12 +376,12 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -384,12 +376,12 @@ export class AppRouteRouteModule extends RouteModule<
} }
public async handle( public async handle(
req: BaseNextRequest, request: NextRequest,
context: AppRouteRouteHandlerContext context: AppRouteRouteHandlerContext
): Promise<Response> { ): Promise<Response> {
try { try {
// Execute the route to get the response. // Execute the route to get the response.
const response = await this.execute(req, context) const response = await this.execute(request, context)
// The response was handled, return it. // The response was handled, return it.
return response return response
......
import type { RouteDefinition } from '../route-definitions/route-definition' import type { RouteDefinition } from '../route-definitions/route-definition'
import type { BaseNextRequest } from '../../base-http' import type { NextRequest } from '../../web/spec-extension/request'
import type { Params } from '../../../shared/lib/router/utils/route-matcher' import type { Params } from '../../../shared/lib/router/utils/route-matcher'
// These are imported weirdly like this because of the way that the bundling // These are imported weirdly like this because of the way that the bundling
...@@ -96,7 +96,7 @@ export abstract class RouteModule< ...@@ -96,7 +96,7 @@ export abstract class RouteModule<
* Handle will handle the request and return a response. * Handle will handle the request and return a response.
*/ */
public abstract handle( public abstract handle(
req: BaseNextRequest, req: NextRequest,
context: RouteModuleHandleContext context: RouteModuleHandleContext
): Promise<Response> ): Promise<Response>
......
...@@ -20,7 +20,7 @@ import { getContentType, getExtension } from './serve-static' ...@@ -20,7 +20,7 @@ import { getContentType, getExtension } from './serve-static'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import { NextUrlWithParsedQuery } from './request-meta' import { NextUrlWithParsedQuery } from './request-meta'
import { IncrementalCacheEntry, IncrementalCacheValue } from './response-cache' import { IncrementalCacheEntry, IncrementalCacheValue } from './response-cache'
import { mockRequest } from './lib/mock-request' import { createRequestResponseMocks } from './lib/mock-request'
import { hasMatch } from '../shared/lib/match-remote-pattern' import { hasMatch } from '../shared/lib/match-remote-pattern'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg' import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import { ImageConfigComplete } from '../shared/lib/image-config' import { ImageConfigComplete } from '../shared/lib/image-config'
...@@ -521,7 +521,7 @@ export async function imageOptimizer( ...@@ -521,7 +521,7 @@ export async function imageOptimizer(
) => Promise<void> ) => Promise<void>
): Promise<{ buffer: Buffer; contentType: string; maxAge: number }> { ): Promise<{ buffer: Buffer; contentType: string; maxAge: number }> {
let upstreamBuffer: Buffer let upstreamBuffer: Buffer
let upstreamType: string | null let upstreamType: string | null | undefined
let maxAge: number let maxAge: number
const { isAbsolute, href, width, mimeType, quality } = paramsResult const { isAbsolute, href, width, mimeType, quality } = paramsResult
...@@ -547,28 +547,30 @@ export async function imageOptimizer( ...@@ -547,28 +547,30 @@ export async function imageOptimizer(
maxAge = getMaxAge(upstreamRes.headers.get('Cache-Control')) maxAge = getMaxAge(upstreamRes.headers.get('Cache-Control'))
} else { } else {
try { try {
const { const mocked = createRequestResponseMocks({
resBuffers, url: href,
req: mockReq, method: _req.method || 'GET',
res: mockRes, headers: _req.headers,
streamPromise: isStreamFinished, socket: _req.socket,
} = mockRequest(href, _req.headers, _req.method || 'GET', _req.connection) })
await handleRequest(mockReq, mockRes, nodeUrl.parse(href, true)) await handleRequest(mocked.req, mocked.res, nodeUrl.parse(href, true))
await isStreamFinished await mocked.res.hasStreamed
if (!mockRes.statusCode) { if (!mocked.res.statusCode) {
console.error('image response failed for', href, mockRes.statusCode) console.error('image response failed for', href, mocked.res.statusCode)
throw new ImageError( throw new ImageError(
mockRes.statusCode, mocked.res.statusCode,
'"url" parameter is valid but internal response is invalid' '"url" parameter is valid but internal response is invalid'
) )
} }
upstreamBuffer = Buffer.concat(resBuffers) upstreamBuffer = Buffer.concat(mocked.res.buffers)
upstreamType = upstreamType =
detectContentType(upstreamBuffer) || mockRes.getHeader('Content-Type') detectContentType(upstreamBuffer) ||
maxAge = getMaxAge(mockRes.getHeader('Cache-Control')) mocked.res.getHeader('Content-Type')
const cacheControl = mocked.res.getHeader('Cache-Control')
maxAge = cacheControl ? getMaxAge(cacheControl) : 0
} catch (err) { } catch (err) {
console.error('upstream image response failed for', href, err) console.error('upstream image response failed for', href, err)
throw new ImageError( throw new ImageError(
......
import { MockedRequest, MockedResponse } from './mock-request'
// We use `Headers` here which is provided by the polyfill.
import '../node-polyfill-fetch'
describe('MockedRequest', () => {
it('should have the correct properties', () => {
const req = new MockedRequest({
url: '/hello',
method: 'POST',
headers: {
'x-foo': 'bar',
},
})
expect(req.url).toBe('/hello')
expect(req.method).toBe('POST')
expect(req.headers).toEqual({
'x-foo': 'bar',
})
})
})
describe('MockedResponse', () => {
it('should merge headers correctly when calling writeHead', () => {
const res = new MockedResponse({})
res.setHeader('x-foo', 'bar')
res.setHeader('x-bar', 'foo')
res.writeHead(200, { 'x-foo': 'bar, foo', 'x-bar': 'foo, bar' })
expect(res.getHeaders()).toEqual({
'x-foo': 'bar, foo',
'x-bar': 'foo, bar',
})
res.writeHead(200, ['x-foo', 'foo, bar', 'x-bar', 'bar, foo'])
expect(res.getHeaders()).toEqual({
'x-foo': 'foo, bar',
'x-bar': 'bar, foo',
})
res.writeHead(200, ['x-foo', ['bar', 'foo'], 'x-bar', ['foo', 'bar']])
expect(res.getHeaders()).toEqual({
'x-foo': 'bar, foo',
'x-bar': 'foo, bar',
})
res.writeHead(200, ['x-foo', 1, 'x-bar', 2])
expect(res.getHeaders()).toEqual({
'x-foo': '1',
'x-bar': '2',
})
})
it('should update the statusMessage after calling writeHead', () => {
const res = new MockedResponse({})
// Default code and status message is 200 and ''.
expect(res.statusCode).toBe(200)
expect(res.statusMessage).toBe('')
res.writeHead(200, 'OK')
expect(res.statusCode).toBe(200)
expect(res.statusMessage).toBe('OK')
res.writeHead(400, 'Bad Request')
expect(res.statusCode).toBe(400)
expect(res.statusMessage).toBe('Bad Request')
})
it('should handle set-cookie headers correctly', () => {
const res = new MockedResponse({})
res.setHeader('set-cookie', ['foo=bar', 'bar=foo'])
expect(res.getHeaders()).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'],
})
res.writeHead(200, { 'Set-Cookie': 'foo=bar2' })
expect(res.getHeaders()).toEqual({
'set-cookie': 'foo=bar2',
})
res.writeHead(200, { 'Set-Cookie': ['foo=bar2', 'bar2=foo'] })
expect(res.getHeaders()).toEqual({
'set-cookie': ['foo=bar2', 'bar2=foo'],
})
})
})
import type { RouteHandlerManagerContext } from '../../../../server/future/route-handler-managers/route-handler-manager' import type { RouteHandlerManagerContext } from '../future/route-handler-managers/route-handler-manager'
import type { RouteDefinition } from '../../../../server/future/route-definitions/route-definition' import type { RouteDefinition } from '../future/route-definitions/route-definition'
import type { RouteModule } from '../../../../server/future/route-modules/route-module' import type { RouteModule } from '../future/route-modules/route-module'
import type { NextRequest } from './spec-extension/request'
import { import { adapter, enhanceGlobals, type AdapterOptions } from './adapter'
adapter,
enhanceGlobals,
type AdapterOptions,
} from '../../../../server/web/adapter'
enhanceGlobals() enhanceGlobals()
import { WebNextRequest } from '../../../../server/base-http/web' import { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'
import { removeTrailingSlash } from '../../../../shared/lib/router/utils/remove-trailing-slash' import { RouteMatcher } from '../future/route-matchers/route-matcher'
import { RouteMatcher } from '../../../../server/future/route-matchers/route-matcher'
type WrapOptions = Partial<Pick<AdapterOptions, 'page'>> type WrapOptions = Partial<Pick<AdapterOptions, 'page'>>
/** /**
* HandlerProvider is a wrapper around a route handler that allows the handler * EdgeRouteModuleWrapper is a wrapper around a route module.
* to be patched and reused.
* *
* This should only be used in the edge runtime. * Note that this class should only be used in the edge runtime.
*/ */
export class EdgeModuleWrapper { export class EdgeRouteModuleWrapper {
private readonly matcher: RouteMatcher private readonly matcher: RouteMatcher
/**
* The constructor is wrapped with private to ensure that it can only be
* constructed by the static wrap method.
*
* @param routeModule the route module to wrap
*/
private constructor( private constructor(
private readonly routeModule: RouteModule<RouteDefinition> private readonly routeModule: RouteModule<RouteDefinition>
) { ) {
...@@ -46,7 +47,7 @@ export class EdgeModuleWrapper { ...@@ -46,7 +47,7 @@ export class EdgeModuleWrapper {
options: WrapOptions = {} options: WrapOptions = {}
) { ) {
// Create the module wrapper. // Create the module wrapper.
const wrapper = new EdgeModuleWrapper(routeModule) const wrapper = new EdgeRouteModuleWrapper(routeModule)
// Return the wrapping function. // Return the wrapping function.
return (opts: AdapterOptions) => { return (opts: AdapterOptions) => {
...@@ -59,14 +60,11 @@ export class EdgeModuleWrapper { ...@@ -59,14 +60,11 @@ export class EdgeModuleWrapper {
} }
} }
private async handler(request: Request): Promise<Response> { private async handler(request: NextRequest): Promise<Response> {
// Setup the handler if it hasn't been setup yet. It is the responsibility // Setup the handler if it hasn't been setup yet. It is the responsibility
// of the module to ensure that this is only called once. // of the module to ensure that this is only called once.
this.routeModule.setup() this.routeModule.setup()
// TODO: (wyattjoh) replace with the unified request type
const req = new WebNextRequest(request)
// Get the pathname for the matcher. Pathnames should not have trailing // Get the pathname for the matcher. Pathnames should not have trailing
// slashes for matching. // slashes for matching.
const pathname = removeTrailingSlash(new URL(request.url).pathname) const pathname = removeTrailingSlash(new URL(request.url).pathname)
...@@ -89,6 +87,6 @@ export class EdgeModuleWrapper { ...@@ -89,6 +87,6 @@ export class EdgeModuleWrapper {
} }
// Get the response from the handler. // Get the response from the handler.
return await this.routeModule.handle(req, context) return await this.routeModule.handle(request, context)
} }
} }
import type { IncomingHttpHeaders } from 'http'
/**
* @internal
*/
export class ReadonlyHeadersError extends Error {
constructor() {
super(
'Headers cannot be modified. Read more: https://nextjs.org/docs/api-reference/headers'
)
}
public static callable() {
throw new ReadonlyHeadersError()
}
}
export type ReadonlyHeaders = Omit<Headers, 'append' | 'delete' | 'set'>
export class HeadersAdapter extends Headers {
private readonly headers: IncomingHttpHeaders
constructor(headers: IncomingHttpHeaders) {
// We've already overridden the methods that would be called, so we're just
// calling the super constructor to ensure that the instanceof check works.
super()
this.headers = new Proxy(headers, {
get(target, prop, receiver) {
// Because this is just an object, we expect that all "get" operations
// are for properties. If it's a "get" for a symbol, we'll just return
// the symbol.
if (typeof prop === 'symbol') return Reflect.get(target, prop, receiver)
const lowercased = prop.toLowerCase()
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find(
(o) => o.toLowerCase() === lowercased
)
// If the original casing doesn't exist, return undefined.
if (typeof original === 'undefined') return
// If the original casing exists, return the value.
return Reflect.get(target, original, receiver)
},
set(target, prop, value) {
if (typeof prop === 'symbol') return Reflect.set(target, prop, value)
const lowercased = prop.toLowerCase()
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find(
(o) => o.toLowerCase() === lowercased
)
// If the original casing doesn't exist, use the prop as the key.
return Reflect.set(target, original ?? prop, value)
},
has(target, prop) {
if (typeof prop === 'symbol') return Reflect.has(target, prop)
const lowercased = prop.toLowerCase()
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find(
(o) => o.toLowerCase() === lowercased
)
// If the original casing doesn't exist, return false.
if (typeof original === 'undefined') return false
// If the original casing exists, return true.
return Reflect.has(target, original)
},
deleteProperty(target, prop) {
if (typeof prop === 'symbol')
return Reflect.deleteProperty(target, prop)
const lowercased = prop.toLowerCase()
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find(
(o) => o.toLowerCase() === lowercased
)
// If the original casing doesn't exist, return true.
if (typeof original === 'undefined') return true
// If the original casing exists, delete the property.
return Reflect.deleteProperty(target, original)
},
})
}
/**
* Seals a Headers instance to prevent modification by throwing an error when
* any mutating method is called.
*/
public static seal(headers: Headers): ReadonlyHeaders {
return new Proxy(headers, {
get(target, prop, receiver) {
switch (prop) {
case 'append':
case 'delete':
case 'set':
return ReadonlyHeadersError.callable
default:
return Reflect.get(target, prop, receiver)
}
},
})
}
/**
* Merges a header value into a string. This stores multiple values as an
* array, so we need to merge them into a string.
*
* @param value a header value
* @returns a merged header value (a string)
*/
private merge(value: string | string[]): string {
if (Array.isArray(value)) return value.join(', ')
return value
}
/**
* Creates a Headers instance from a plain object or a Headers instance.
*
* @param headers a plain object or a Headers instance
* @returns a headers instance
*/
public static from(headers: IncomingHttpHeaders | Headers): Headers {
if (headers instanceof Headers) return headers
return new HeadersAdapter(headers)
}
public append(name: string, value: string): void {
const existing = this.headers[name]
if (typeof existing === 'string') {
this.headers[name] = [existing, value]
} else if (Array.isArray(existing)) {
existing.push(value)
} else {
this.headers[name] = value
}
}
public delete(name: string): void {
delete this.headers[name]
}
public get(name: string): string | null {
const value = this.headers[name]
if (typeof value !== 'undefined') return this.merge(value)
return null
}
public has(name: string): boolean {
return typeof this.headers[name] !== 'undefined'
}
public set(name: string, value: string): void {
this.headers[name] = value
}
public forEach(
callbackfn: (value: string, name: string, parent: Headers) => void,
thisArg?: any
): void {
for (const [name, value] of this.entries()) {
callbackfn.call(thisArg, value, name, this)
}
}
public *entries(): IterableIterator<[string, string]> {
for (const key of Object.keys(this.headers)) {
const name = key.toLowerCase()
// We assert here that this is a string because we got it from the
// Object.keys() call above.
const value = this.get(name) as string
yield [name, value] as [string, string]
}
}
public *keys(): IterableIterator<string> {
for (const key of Object.keys(this.headers)) {
const name = key.toLowerCase()
yield name
}
}
public *values(): IterableIterator<string> {
for (const key of Object.keys(this.headers)) {
// We assert here that this is a string because we got it from the
// Object.keys() call above.
const value = this.get(key) as string
yield value
}
}
public [Symbol.iterator](): IterableIterator<[string, string]> {
return this.entries()
}
}
import type { BaseNextRequest } from '../../../base-http'
import type { NodeNextRequest } from '../../../base-http/node'
import type { WebNextRequest } from '../../../base-http/web'
import { getRequestMeta } from '../../../request-meta'
import { fromNodeHeaders } from '../../utils'
import { NextRequest } from '../request'
export class NextRequestAdapter {
public static fromBaseNextRequest(request: BaseNextRequest): NextRequest {
// TODO: look at refining this check
if ('request' in request && (request as WebNextRequest).request) {
return NextRequestAdapter.fromWebNextRequest(request as WebNextRequest)
}
return NextRequestAdapter.fromNodeNextRequest(request as NodeNextRequest)
}
public static fromNodeNextRequest(request: NodeNextRequest): NextRequest {
// HEAD and GET requests can not have a body.
let body: BodyInit | null = null
if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {
// @ts-expect-error - this is handled by undici, when streams/web land use it instead
body = request.body
}
let url: URL
if (request.url.startsWith('http')) {
url = new URL(request.url)
} else {
// Grab the full URL from the request metadata.
const base = getRequestMeta(request, '__NEXT_INIT_URL')
if (!base) throw new Error('Invariant: missing url on request')
url = new URL(request.url, base)
}
return new NextRequest(url, {
body,
method: request.method,
headers: fromNodeHeaders(request.headers),
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: 'half',
// geo
// ip
// nextConfig
})
}
public static fromWebNextRequest(request: WebNextRequest): NextRequest {
// HEAD and GET requests can not have a body.
let body: ReadableStream | null = null
if (request.method !== 'GET' && request.method !== 'HEAD') {
body = request.body
}
return new NextRequest(request.url, {
body,
method: request.method,
headers: fromNodeHeaders(request.headers),
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: 'half',
// geo
// ip
// nextConfig
})
}
}
// We use `Headers` here which is provided by the polyfill.
import '../../../node-polyfill-fetch'
import { RequestCookies } from '../cookies'
import {
ReadonlyRequestCookiesError,
RequestCookiesAdapter,
} from './request-cookies'
describe('RequestCookiesAdapter', () => {
it('should be able to create a new instance from a RequestCookies', () => {
const headers = new Headers({ cookie: 'foo=bar; bar=foo' })
const cookies = new RequestCookies(headers)
const sealed = RequestCookiesAdapter.seal(cookies)
expect(sealed).toBeInstanceOf(RequestCookies)
expect(sealed.get('foo')).toEqual({ name: 'foo', value: 'bar' })
expect(sealed.get('bar')).toEqual({ name: 'bar', value: 'foo' })
// These methods are not available on the sealed instance
expect(() => (sealed as any).set('foo', 'bar2')).toThrowError(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).delete('foo')).toThrowError(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).clear()).toThrowError(
ReadonlyRequestCookiesError
)
// Ensure nothing was actually changed.
expect(sealed.get('foo')).toEqual({ name: 'foo', value: 'bar' })
expect(sealed.get('bar')).toEqual({ name: 'bar', value: 'foo' })
})
it('should be able to create a new instance from an empty RequestCookies', () => {
const headers = new Headers({})
const cookies = new RequestCookies(headers)
const sealed = RequestCookiesAdapter.seal(cookies)
expect(sealed).toBeInstanceOf(RequestCookies)
expect(sealed.get('foo')).toEqual(undefined)
expect(sealed.get('bar')).toEqual(undefined)
// These methods are not available on the sealed instance
expect(() => (sealed as any).set('foo', 'bar2')).toThrowError(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).delete('foo')).toThrowError(
ReadonlyRequestCookiesError
)
expect(() => (sealed as any).clear()).toThrowError(
ReadonlyRequestCookiesError
)
// Ensure nothing was actually changed.
expect(sealed.get('foo')).toEqual(undefined)
expect(sealed.get('bar')).toEqual(undefined)
})
})
import type { RequestCookies } from '../cookies'
/**
* @internal
*/
export class ReadonlyRequestCookiesError extends Error {
constructor() {
super(
'ReadonlyRequestCookies cannot be modified. Read more: https://nextjs.org/docs/api-reference/cookies'
)
}
public static callable() {
throw new ReadonlyRequestCookiesError()
}
}
export type ReadonlyRequestCookies = Omit<
RequestCookies,
'clear' | 'delete' | 'set'
>
export class RequestCookiesAdapter {
public static seal(cookies: RequestCookies): ReadonlyRequestCookies {
return new Proxy(cookies, {
get(target, prop) {
switch (prop) {
case 'clear':
case 'delete':
case 'set':
return ReadonlyRequestCookiesError.callable
default:
return Reflect.get(target, prop)
}
},
})
}
}
import { toNodeHeaders } from './utils'
// We use `Headers` here which is provided by the polyfill.
import '../node-polyfill-fetch'
describe('toNodeHeaders', () => {
it('should handle multiple set-cookie headers correctly', () => {
const headers = new Headers()
headers.append('set-cookie', 'foo=bar')
headers.append('set-cookie', 'bar=foo')
expect(toNodeHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'],
})
})
it('should handle a single set-cookie header correctly', () => {
const headers = new Headers()
headers.append('set-cookie', 'foo=bar')
expect(toNodeHeaders(headers)).toEqual({
'set-cookie': 'foo=bar',
})
})
it('should handle a single set-cookie header with multiple cookies correctly', () => {
const headers = new Headers()
headers.append('set-cookie', 'foo=bar, bar=foo')
expect(toNodeHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'],
})
headers.append('set-cookie', 'baz=qux')
expect(toNodeHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo', 'baz=qux'],
})
})
it('should handle mixed case set-cookie headers correctly', () => {
const headers = new Headers()
headers.append('set-cookie', 'foo=bar')
headers.append('Set-Cookie', 'bar=foo')
expect(toNodeHeaders(headers)).toEqual({
'set-cookie': ['foo=bar', 'bar=foo'],
})
})
it('should return an empty object when no headers are provided', () => {
expect(toNodeHeaders()).toEqual({})
})
})
...@@ -102,7 +102,7 @@ export function toNodeHeaders(headers?: Headers): OutgoingHttpHeaders { ...@@ -102,7 +102,7 @@ export function toNodeHeaders(headers?: Headers): OutgoingHttpHeaders {
// set-cookie headers. We need to merge them into one header array // set-cookie headers. We need to merge them into one header array
// to represent all the cookies. // to represent all the cookies.
cookies.push(...splitCookiesString(value)) cookies.push(...splitCookiesString(value))
result[key] = cookies result[key] = cookies.length === 1 ? cookies[0] : cookies
} else { } else {
result[key] = value result[key] = value
} }
......
import { getHostname } from './get-hostname'
describe('getHostname', () => {
describe('from URL', () => {
it.each([
{ url: 'http://example.com', hostname: 'example.com' },
{ url: 'http://example.com/', hostname: 'example.com' },
{ url: 'http://example.com:3000', hostname: 'example.com' },
{ url: 'https://example.com', hostname: 'example.com' },
{ url: 'https://example.com/', hostname: 'example.com' },
{ url: 'https://example.com:3000', hostname: 'example.com' },
{ url: 'http://localhost', hostname: 'localhost' },
{ url: 'http://localhost/', hostname: 'localhost' },
{ url: 'http://localhost:3000', hostname: 'localhost' },
{ url: 'http://127.0.0.1', hostname: '127.0.0.1' },
{ url: 'http://127.0.0.1/', hostname: '127.0.0.1' },
{ url: 'http://127.0.0.1:3000', hostname: '127.0.0.1' },
{ url: 'http://8.8.8.8', hostname: '8.8.8.8' },
{ url: 'http://8.8.8.8/', hostname: '8.8.8.8' },
{ url: 'http://8.8.8.8:3000', hostname: '8.8.8.8' },
])('should return $hostname for $url', ({ url, hostname }) => {
const parsed = new URL(url)
// Base case.
expect(getHostname(parsed)).toBe(hostname)
// With headers.
expect(getHostname(parsed, { host: parsed.host })).toBe(hostname)
// With an empty headers array.
expect(getHostname(parsed, { host: [] })).toBe(hostname)
// With a headers array.
expect(getHostname({}, { host: [parsed.host] })).toBe(undefined)
})
})
it('should return undefined for empty input', () => {
expect(getHostname({})).toBe(undefined)
expect(getHostname({}, { host: [] })).toBe(undefined)
})
})
...@@ -9,9 +9,15 @@ import type { OutgoingHttpHeaders } from 'http' ...@@ -9,9 +9,15 @@ import type { OutgoingHttpHeaders } from 'http'
export function getHostname( export function getHostname(
parsed: { hostname?: string | null }, parsed: { hostname?: string | null },
headers?: OutgoingHttpHeaders headers?: OutgoingHttpHeaders
) { ): string | undefined {
return ((!Array.isArray(headers?.host) && headers?.host) || parsed.hostname) // Get the hostname from the headers if it exists, otherwise use the parsed
?.toString() // hostname.
.split(':')[0] let hostname: string
.toLowerCase() if (headers?.host && !Array.isArray(headers.host)) {
hostname = headers.host.toString().split(':')[0]
} else if (parsed.hostname) {
hostname = parsed.hostname
} else return
return hostname.toLowerCase()
} }
...@@ -6,16 +6,26 @@ createNextDescribe( ...@@ -6,16 +6,26 @@ createNextDescribe(
files: __dirname, files: __dirname,
}, },
({ next }) => { ({ next }) => {
it('should work with node runtime', async () => { it.each(['edge', 'node'])(
const res = await next.fetch('/api/') 'should handle trailing slash for %s runtime',
const html = await res.text() async (runtime) => {
expect(html).toContain('Hello World') let res = await next.fetch(`/runtime/${runtime}`, {
redirect: 'manual',
}) })
it('should work edge node runtime', async () => { expect(res.status).toEqual(308)
const res = await next.fetch('/api/edge/') expect(res.headers.get('location')).toEndWith(`/runtime/${runtime}/`)
const html = await res.text()
expect(html).toContain('Hello World') res = await next.fetch(`/runtime/${runtime}/`, {
redirect: 'manual',
})
expect(res.status).toEqual(200)
await expect(res.json()).resolves.toEqual({
url: `/runtime/${runtime}/`,
nextUrl: `/runtime/${runtime}/`,
}) })
} }
)
}
) )
export async function GET() {
return new Response('Hello World')
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
export const runtime = 'edge' export const runtime = 'edge'
export async function GET() { export { GET } from '../../../handler'
return new Response('Hello World')
}
import { NextRequest, NextResponse } from 'next/server'
export const GET = (req: NextRequest) => {
const url = new URL(req.url)
return NextResponse.json({
url: url.pathname,
nextUrl: req.nextUrl.pathname,
})
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment