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

Base Http for BaseServer #32999

Merged
merged 16 commits into from Jan 14, 2022
Merged
Expand Up @@ -3,6 +3,7 @@ import { IncomingMessage, ServerResponse } from 'http'
import { apiResolver } from '../../../../server/api-utils'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
import { DecodeError } from '../../../../shared/lib/utils'
import { NodeNextResponse, NodeNextRequest } from '../../../../server/base-http'

export function getApiHandler(ctx: ServerlessHandlerCtx) {
const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx
Expand All @@ -13,7 +14,15 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
normalizeDynamicRouteParams,
} = getUtils(ctx)

return async (req: IncomingMessage, res: ServerResponse) => {
return async (
rawReq: NodeNextRequest | IncomingMessage,
rawRes: NodeNextResponse | ServerResponse
) => {
const req =
rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq
const res =
rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes

try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
Expand Down Expand Up @@ -41,8 +50,8 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
}

await apiResolver(
req,
res,
req.originalRequest,
res.originalResponse,
Object.assign({}, parsedUrl.query, params),
await pageModule,
encodedPreviewProps,
Expand All @@ -53,7 +62,7 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {

if (err instanceof DecodeError) {
res.statusCode = 400
res.end('Bad Request')
res.body('Bad Request').send()
} else {
// Throw the error to crash the serverless function
throw err
Expand Down
Expand Up @@ -25,6 +25,7 @@ import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { NextConfig } from '../../../../server/config'
import { addRequestMeta } from '../../../../server/request-meta'
import { BaseNextRequest } from '../../../../server/base-http'

const getCustomRouteMatcher = pathMatch(true)

Expand Down Expand Up @@ -85,7 +86,10 @@ export function getUtils({
defaultRouteMatches = dynamicRouteMatcher(page) as ParsedUrlQuery
}

function handleRewrites(req: IncomingMessage, parsedUrl: UrlWithParsedQuery) {
function handleRewrites(
req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery
) {
for (const rewrite of rewrites) {
const matcher = getCustomRouteMatcher(rewrite.source)
let params = matcher(parsedUrl.pathname)
Expand Down Expand Up @@ -150,15 +154,18 @@ export function getUtils({
return parsedUrl
}

function handleBasePath(req: IncomingMessage, parsedUrl: UrlWithParsedQuery) {
function handleBasePath(
req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery
) {
// always strip the basePath if configured since it is required
req.url = req.url!.replace(new RegExp(`^${basePath}`), '') || '/'
parsedUrl.pathname =
parsedUrl.pathname!.replace(new RegExp(`^${basePath}`), '') || '/'
}

function getParamsFromRouteMatches(
req: IncomingMessage,
req: BaseNextRequest | IncomingMessage,
renderOpts?: any,
detectedLocale?: string
) {
Expand Down Expand Up @@ -269,7 +276,10 @@ export function getUtils({
return pathname
}

function normalizeVercelUrl(req: IncomingMessage, trustQuery: boolean) {
function normalizeVercelUrl(
req: BaseNextRequest | IncomingMessage,
trustQuery: boolean
) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
Expand Down Expand Up @@ -374,7 +384,7 @@ export function getUtils({
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale
addRequestMeta(req, '__nextIsLocaleDomain', true)
addRequestMeta(req as any, '__nextIsLocaleDomain', true)
}

// if not domain specific locale use accept-language preferred
Expand All @@ -394,7 +404,7 @@ export function getUtils({
...parsedUrl,
pathname: localePathResult.pathname,
})
addRequestMeta(req, '__nextStrippedLocale', true)
addRequestMeta(req as any, '__nextStrippedLocale', true)
parsedUrl.pathname = localePathResult.pathname
}

Expand Down
9 changes: 5 additions & 4 deletions packages/next/server/api-utils.ts
Expand Up @@ -10,6 +10,7 @@ import { sendEtagResponse } from './send-payload'
import generateETag from 'next/dist/compiled/etag'
import isError from '../lib/is-error'
import { interopDefault } from '../lib/interop-default'
import { BaseNextRequest, BaseNextResponse } from './base-http'

export type NextApiRequestCookies = { [key: string]: string }
export type NextApiRequestQuery = { [key: string]: string | string[] }
Expand Down Expand Up @@ -141,7 +142,7 @@ export async function apiResolver(
* @param req request object
*/
export async function parseBody(
req: NextApiRequest,
req: IncomingMessage,
limit: string | number
): Promise<any> {
let contentType
Expand Down Expand Up @@ -335,11 +336,11 @@ const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`

export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)
const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)
export const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)

export function tryGetPreviewData(
req: IncomingMessage,
res: ServerResponse,
req: IncomingMessage | BaseNextRequest,
res: ServerResponse | BaseNextResponse,
options: __ApiPreviewProps
): PreviewData {
// Read cached preview data if present
Expand Down