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

Implement middleware support for Turbopack #46397

Merged
merged 5 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/next/src/build/analysis/get-page-static-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ async function tryToReadFile(filePath: string, shouldThrow: boolean) {
}
}

function getMiddlewareMatchers(
export function getMiddlewareMatchers(
matcherOrMatchers: unknown,
nextConfig: NextConfig
): MiddlewareMatcher[] {
Expand Down
60 changes: 57 additions & 3 deletions packages/next/src/server/lib/route-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ import { RouteKind } from '../future/route-kind'
import { DefaultRouteMatcherManager } from '../future/route-matcher-managers/default-route-matcher-manager'
import { RouteMatch } from '../future/route-matches/route-match'
import type { PageChecker, Route } from '../router'
import { getMiddlewareMatchers } from '../../build/analysis/get-page-static-info'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
import { join } from 'path'

type MiddlewareConfig = {
matcher: string[]
files: string[]
}
type RouteResult =
| {
type: 'rewrite'
Expand Down Expand Up @@ -48,7 +55,11 @@ class DevRouteMatcherManager extends DefaultRouteMatcherManager {
}
}

export async function makeResolver(dir: string, nextConfig: NextConfig) {
export async function makeResolver(
dir: string,
nextConfig: NextConfig,
middleware: MiddlewareConfig
) {
const url = require('url') as typeof import('url')
const { default: Router } = require('../router') as typeof import('../router')
const { getPathMatch } =
Expand All @@ -65,14 +76,52 @@ export async function makeResolver(dir: string, nextConfig: NextConfig) {
const devServer = new DevServer({
dir,
conf: nextConfig,
hostname: 'localhost',
port: 3000,
Comment on lines +79 to +80
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both are necessary for the devServer.attachRequestMeta(req, parsedUrl) call to initialize the __NEXT_INIT_URL meta for edge invocation.

})

await devServer.matchers.reload()

// @ts-expect-error
devServer.customRoutes = await loadCustomRoutes(nextConfig)
const matchers = getMiddlewareMatchers(middleware.matcher, nextConfig)
// @ts-expect-error
devServer.middleware = {
page: '/',
match: getMiddlewareRouteMatcher(matchers),
matchers,
}

type GetEdgeFunctionInfo =
typeof DevServer['prototype']['getEdgeFunctionInfo']
const getEdgeFunctionInfo = (
original: GetEdgeFunctionInfo
): GetEdgeFunctionInfo => {
return (params: { page: string; middleware: boolean }) => {
if (params.middleware) {
return {
name: 'middleware',
paths: middleware.files.map((file) => join(process.cwd(), file)),
env: [],
wasm: [],
assets: [],
}
}
return original(params)
}
}
// @ts-expect-error protected
devServer.getEdgeFunctionInfo = getEdgeFunctionInfo(
// @ts-expect-error protected
devServer.getEdgeFunctionInfo.bind(devServer)
)
// @ts-expect-error protected
devServer.hasMiddleware = () => true

const routeResults = new WeakMap<any, string>()
const routes = devServer.generateRoutes.bind(devServer)()
const routes = devServer.generateRoutes()
Comment on lines -75 to +127
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stylistic nits, the .bind()() doesn't accomplish anything and is kinda expensive.

// @ts-expect-error protected
const catchAllMiddleware = devServer.generateCatchAllMiddlewareRoute(true)

routes.matchers = new DevRouteMatcherManager(
// @ts-expect-error internal method
Expand All @@ -81,6 +130,7 @@ export async function makeResolver(dir: string, nextConfig: NextConfig) {

const router = new Router({
...routes,
catchAllMiddleware,
catchAllRoute: {
match: getPathMatch('/:path*'),
name: 'catchall route',
Expand Down Expand Up @@ -112,6 +162,7 @@ export async function makeResolver(dir: string, nextConfig: NextConfig) {
route.type === 'redirect' ||
route.type === 'header' ||
route.name === 'catchall route' ||
route.name === 'middleware catchall' ||
route.name?.includes('check')
return matches
})
Expand All @@ -122,9 +173,12 @@ export async function makeResolver(dir: string, nextConfig: NextConfig) {
) {
const req = new NodeNextRequest(_req)
const res = new NodeNextResponse(_res)
const parsedUrl = url.parse(req.url!, true)
// @ts-expect-error protected
devServer.attachRequestMeta(req, parsedUrl)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is necessary to initialize the __NEXT_INIT_URL for the edge invocation.

;(req as any)._initUrl = req.url

await router.execute.bind(router)(req, res, url.parse(req.url!, true))
await router.execute(req, res, parsedUrl)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto .bind()()


if (!res.originalResponse.headersSent) {
res.setHeader('x-nextjs-route-result', '1')
Expand Down