Skip to content

Commit

Permalink
turbopack: pass dev server address to router
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Apr 6, 2023
1 parent ebdc890 commit 31a0257
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 11 deletions.
17 changes: 10 additions & 7 deletions packages/next-swc/crates/next-core/js/src/entry/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import { Buffer } from "node:buffer";
import { createServer, makeRequest } from "@vercel/turbopack-next/ipc/server";
import { toPairs } from "@vercel/turbopack-next/internal/headers";
import { makeResolver, RouteResult } from "next/dist/server/lib/route-resolver";
import { makeResolver, RouteResult, ServerAddress } from "next/dist/server/lib/route-resolver";
import loadConfig from "next/dist/server/config";
import { PHASE_DEVELOPMENT_SERVER } from "next/dist/shared/lib/constants";

Expand Down Expand Up @@ -52,7 +52,8 @@ let resolveRouteMemo: Promise<
>;

async function getResolveRoute(
dir: string
dir: string,
serverAddr: Partial<ServerAddress>
): ReturnType<
typeof import("next/dist/server/lib/route-resolver").makeResolver
> {
Expand All @@ -63,20 +64,22 @@ async function getResolveRoute(
undefined,
true
);

return await makeResolver(dir, nextConfig, {
const middlewareCfg = {
files: middlewareChunkGroup.filter((f) => /\.[mc]?js$/.test(f)),
matcher: middlewareConfig.matcher,
});
}

return await makeResolver(dir, nextConfig, middlewareCfg, serverAddr);
}

export default async function route(
ipc: Ipc<RouterRequest, IpcOutgoingMessage>,
routerRequest: RouterRequest,
dir: string
dir: string,
serverAddr: Partial<ServerAddress>
) {
const [resolveRoute, server] = await Promise.all([
(resolveRouteMemo ??= getResolveRoute(dir)),
(resolveRouteMemo ??= getResolveRoute(dir, serverAddr)),
createServer(),
]);

Expand Down
5 changes: 5 additions & 0 deletions packages/next-swc/crates/next-core/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ async fn route_internal(
let Some(dir) = to_sys_path(project_path).await? else {
bail!("Next.js requires a disk path to check for valid routes");
};
let server_addr = server_addr.await?;
let result = evaluate(
router_asset,
project_path,
Expand All @@ -396,6 +397,10 @@ async fn route_internal(
vec![
JsonValueVc::cell(request),
JsonValueVc::cell(dir.to_string_lossy().into()),
JsonValueVc::cell(json!({
"hostname": server_addr.ip(),
"port": server_addr.port(),
})),
],
CompletionsVc::all(vec![next_config_changed, routes_changed]),
/* debug */ false,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
const origin = new URL(req.url).origin;
const res = await fetch(`${origin}/api/endpoint`);
const json = await res.json();
return NextResponse.json(json);
}

export const config = {
matcher: '/fetch-endpoint',
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/** @type {import('next').NextConfig} */
module.exports = {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function handler(_req, res) {
res.status(200).json({ name: 'John Doe' })
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react'

export default function Foo() {
useEffect(() => {
// Only run on client
import('@turbo/pack-test-harness').then(runTests)
})

return 'index'
}

function runTests() {
it('should include custom env fields in middleware process', async () => {
const res = await fetch('/fetch-endpoint')
const env = await res.json()
expect(env).toHaveProperty('name', 'John Doe')
})
}
14 changes: 10 additions & 4 deletions packages/next/src/server/lib/route-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,16 @@ import {
} from '../../shared/lib/constants'
import type { BaseNextRequest } from '../base-http'

type MiddlewareConfig = {
export type MiddlewareConfig = {
matcher: string[]
files: string[]
}

export type ServerAddress = {
hostname: string
port: number
}

export type RouteResult =
| {
type: 'rewrite'
Expand Down Expand Up @@ -78,7 +83,8 @@ class DevRouteMatcherManager extends DefaultRouteMatcherManager {
export async function makeResolver(
dir: string,
nextConfig: NextConfig,
middleware: MiddlewareConfig
middleware: MiddlewareConfig,
serverAddr: Partial<ServerAddress>
) {
const url = require('url') as typeof import('url')
const { default: Router } = require('../router') as typeof import('../router')
Expand Down Expand Up @@ -126,8 +132,8 @@ export async function makeResolver(
const devServer = new TurbopackDevServerProxy({
dir,
conf: nextConfig,
hostname: 'localhost',
port: 3000,
hostname: serverAddr.hostname || 'localhost',
port: serverAddr.port || 3000,
})

await devServer.matchers.reload()
Expand Down

0 comments on commit 31a0257

Please sign in to comment.