* This method gets all middleware matchers and execute them when the request * matches. It will make sure that each middleware exists and is compiled and * ready to be invoked. The development server will decorate it to add warns * and errors with rich traces.
(params: {
request: NodeNextRequest
response: NodeNextResponse
parsedUrl: ParsedUrl
parsed: NextUrlWithParsedQuery
onWarning?: (warning: Error) => void
})
| 1613 | * and errors with rich traces. |
| 1614 | */ |
| 1615 | protected async runMiddleware(params: { |
| 1616 | request: NodeNextRequest |
| 1617 | response: NodeNextResponse |
| 1618 | parsedUrl: ParsedUrl |
| 1619 | parsed: NextUrlWithParsedQuery |
| 1620 | onWarning?: (warning: Error) => void |
| 1621 | }) { |
| 1622 | if (process.env.NEXT_MINIMAL) { |
| 1623 | throw new Error( |
| 1624 | 'invariant: runMiddleware should not be called in minimal mode' |
| 1625 | ) |
| 1626 | } |
| 1627 | |
| 1628 | // Middleware is skipped for on-demand revalidate requests |
| 1629 | if ( |
| 1630 | checkIsOnDemandRevalidate(params.request, this.renderOpts.previewProps) |
| 1631 | .isOnDemandRevalidate |
| 1632 | ) { |
| 1633 | return { |
| 1634 | response: new Response(null, { headers: { 'x-middleware-next': '1' } }), |
| 1635 | } as FetchEventResult |
| 1636 | } |
| 1637 | |
| 1638 | let url: string |
| 1639 | |
| 1640 | if (this.nextConfig.skipProxyUrlNormalize) { |
| 1641 | url = getRequestMeta(params.request, 'initURL')! |
| 1642 | } else { |
| 1643 | // For middleware to "fetch" we must always provide an absolute URL |
| 1644 | const query = urlQueryToSearchParams(params.parsed.query).toString() |
| 1645 | const locale = getRequestMeta(params.request, 'locale') |
| 1646 | |
| 1647 | url = `${getRequestMeta(params.request, 'initProtocol')}://${ |
| 1648 | this.fetchHostname || 'localhost' |
| 1649 | }:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${ |
| 1650 | query ? `?${query}` : '' |
| 1651 | }` |
| 1652 | } |
| 1653 | |
| 1654 | if (!url.startsWith('http')) { |
| 1655 | throw new Error( |
| 1656 | 'To use middleware you must provide a `hostname` and `port` to the Next.js Server' |
| 1657 | ) |
| 1658 | } |
| 1659 | |
| 1660 | const page: { |
| 1661 | name?: string |
| 1662 | params?: { [key: string]: string | string[] } |
| 1663 | } = {} |
| 1664 | |
| 1665 | const middleware = await this.getMiddleware() |
| 1666 | if (!middleware) { |
| 1667 | return { finished: false } |
| 1668 | } |
| 1669 | if (!(await this.hasMiddleware(middleware.page))) { |
| 1670 | return { finished: false } |
| 1671 | } |
| 1672 |
no test coverage detected