next.js/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts
middleware-route-matcher.ts41 lines1006 B
import type { BaseNextRequest } from '../../../../server/base-http'
import type { ProxyMatcher } from '../../../../build/analysis/get-page-static-info'
import type { Params } from '../../../../server/request/params'
import { matchHas } from './prepare-destination'

export interface MiddlewareRouteMatch {
  (
    pathname: string | null | undefined,
    request: BaseNextRequest,
    query: Params
  ): boolean
}

export function getMiddlewareRouteMatcher(
  matchers: ProxyMatcher[]
): MiddlewareRouteMatch {
  return (
    pathname: string | null | undefined,
    req: BaseNextRequest,
    query: Params
  ) => {
    for (const matcher of matchers) {
      const routeMatch = new RegExp(matcher.regexp).exec(pathname!)
      if (!routeMatch) {
        continue
      }

      if (matcher.has || matcher.missing) {
        const hasParams = matchHas(req, query, matcher.has, matcher.missing)
        if (!hasParams) {
          continue
        }
      }

      return true
    }

    return false
  }
}
Quest for Codev2.0.0
/
SIGN IN