rsnext/packages/next/shared/lib/router/utils/parse-next-url.ts
Malte Ubl 6da769129e
Reduce hello-world middleware bundle size from 128k to 88k (#35512)
Moves two utility functions from `server/router.ts` into their own file. This avoids the middleware pulling in the full Next.js router into its bundle.

There are probably more opportunities like this, but this is a good start. Middleware should likely be bundled by a non-chunking optimizing compiler.
2022-03-22 14:54:05 +00:00

54 lines
1.5 KiB
TypeScript

import { getCookieParser } from '../../../../server/api-utils'
import { getLocaleMetadata } from '../../i18n/get-locale-metadata'
import { parseUrl } from './parse-url'
import type { NextConfig, DomainLocale } from '../../../../server/config-shared'
import type { ParsedUrl } from './parse-url'
import type { PathLocale } from '../../i18n/normalize-locale-path'
import { hasBasePath, replaceBasePath } from '../../../../server/router-utils'
interface Params {
headers?: { [key: string]: string | string[] | undefined }
nextConfig: NextConfig
url?: string
}
export function parseNextUrl({ headers, nextConfig, url = '/' }: Params) {
const urlParsed: ParsedNextUrl = parseUrl(url)
const { basePath } = nextConfig
if (basePath && hasBasePath(urlParsed.pathname, basePath)) {
urlParsed.pathname = replaceBasePath(urlParsed.pathname, basePath)
urlParsed.basePath = basePath
}
if (nextConfig.i18n) {
urlParsed.locale = getLocaleMetadata({
cookies: getCookieParser(headers || {}),
headers: headers,
nextConfig: {
basePath: nextConfig.basePath,
i18n: nextConfig.i18n,
trailingSlash: nextConfig.trailingSlash,
},
url: urlParsed,
})
if (urlParsed.locale?.path.detectedLocale) {
urlParsed.pathname = urlParsed.locale.path.pathname
}
}
return urlParsed
}
export interface ParsedNextUrl extends ParsedUrl {
basePath?: string
locale?: {
defaultLocale: string
domain?: DomainLocale
locale: string
path: PathLocale
redirect?: string
trailingSlash?: boolean
}
}