Unverified Commit 964a92a2 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add node middleware handling for turbopack (#76360)

Continuation of https://github.com/vercel/next.js/pull/75624 this adds
the same support for turbopack and enables the related test suites.
parent b60bb5e7
...@@ -7,7 +7,7 @@ use next_core::{ ...@@ -7,7 +7,7 @@ use next_core::{
next_edge::entry::wrap_edge_entry, next_edge::entry::wrap_edge_entry,
next_manifests::{EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2, Regions}, next_manifests::{EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2, Regions},
next_server::{get_server_runtime_entries, ServerContextType}, next_server::{get_server_runtime_entries, ServerContextType},
util::{parse_config_from_source, MiddlewareMatcherKind}, util::{parse_config_from_source, MiddlewareMatcherKind, NextRuntime},
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
...@@ -16,12 +16,13 @@ use turbo_tasks_fs::{self, File, FileContent, FileSystemPath}; ...@@ -16,12 +16,13 @@ use turbo_tasks_fs::{self, File, FileContent, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::AssetContent, asset::AssetContent,
chunk::{ chunk::{
availability_info::AvailabilityInfo, ChunkGroupType, ChunkingContextExt, EvaluatableAsset, availability_info::AvailabilityInfo, ChunkGroupType, ChunkingContext, ChunkingContextExt,
EntryChunkGroupResult, EvaluatableAsset,
}, },
context::AssetContext, context::AssetContext,
module::Module, module::Module,
module_graph::GraphEntries, module_graph::GraphEntries,
output::OutputAssets, output::{OutputAsset, OutputAssets},
reference_type::{EntryReferenceSubType, ReferenceType}, reference_type::{EntryReferenceSubType, ReferenceType},
source::Source, source::Source,
virtual_output::VirtualOutputAsset, virtual_output::VirtualOutputAsset,
...@@ -29,6 +30,7 @@ use turbopack_core::{ ...@@ -29,6 +30,7 @@ use turbopack_core::{
use turbopack_ecmascript::chunk::EcmascriptChunkPlaceable; use turbopack_ecmascript::chunk::EcmascriptChunkPlaceable;
use crate::{ use crate::{
nft_json::NftJsonAsset,
paths::{ paths::{
all_paths_in_root, all_server_paths, get_asset_paths_from_root, get_js_paths_from_root, all_paths_in_root, all_server_paths, get_asset_paths_from_root, get_js_paths_from_root,
get_wasm_paths_from_root, paths_to_bindings, wasm_paths_to_bindings, get_wasm_paths_from_root, paths_to_bindings, wasm_paths_to_bindings,
...@@ -40,6 +42,7 @@ use crate::{ ...@@ -40,6 +42,7 @@ use crate::{
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct MiddlewareEndpoint { pub struct MiddlewareEndpoint {
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
build_id: RcStr,
asset_context: ResolvedVc<Box<dyn AssetContext>>, asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
...@@ -51,6 +54,7 @@ impl MiddlewareEndpoint { ...@@ -51,6 +54,7 @@ impl MiddlewareEndpoint {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new( pub fn new(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
build_id: RcStr,
asset_context: ResolvedVc<Box<dyn AssetContext>>, asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>, source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>, app_dir: Option<ResolvedVc<FileSystemPath>>,
...@@ -58,6 +62,7 @@ impl MiddlewareEndpoint { ...@@ -58,6 +62,7 @@ impl MiddlewareEndpoint {
) -> Vc<Self> { ) -> Vc<Self> {
Self { Self {
project, project,
build_id,
asset_context, asset_context,
source, source,
app_dir, app_dir,
...@@ -67,7 +72,7 @@ impl MiddlewareEndpoint { ...@@ -67,7 +72,7 @@ impl MiddlewareEndpoint {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn entry_module(&self) -> Vc<Box<dyn Module>> { async fn entry_module(&self) -> Result<Vc<Box<dyn Module>>> {
let userland_module = self let userland_module = self
.asset_context .asset_context
.process( .process(
...@@ -82,12 +87,17 @@ impl MiddlewareEndpoint { ...@@ -82,12 +87,17 @@ impl MiddlewareEndpoint {
userland_module, userland_module,
); );
wrap_edge_entry( let config = parse_config_from_source(userland_module, NextRuntime::Edge).await?;
if matches!(config.runtime, NextRuntime::NodeJs) {
return Ok(module);
}
Ok(wrap_edge_entry(
*self.asset_context, *self.asset_context,
self.project.project_path(), self.project.project_path(),
module, module,
"middleware".into(), "middleware".into(),
) ))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -134,42 +144,48 @@ impl MiddlewareEndpoint { ...@@ -134,42 +144,48 @@ impl MiddlewareEndpoint {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> { async fn node_chunk(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> {
let this = self.await?; let this = self.await?;
let userland_module = self.userland_module(); let chunking_context = this.project.server_chunking_context(false);
let config = parse_config_from_source(userland_module);
let edge_files = self.edge_files();
let mut output_assets = edge_files.owned().await?;
let node_root = this.project.node_root();
let node_root_value = node_root.await?;
let file_paths_from_root = get_js_paths_from_root(&node_root_value, &output_assets).await?; let userland_module = self.entry_module().to_resolved().await?;
let module_graph = this
.project
.module_graph(*userland_module, ChunkGroupType::Entry);
let all_output_assets = all_assets_from_entries(edge_files).await?; let Some(module) = ResolvedVc::try_downcast(userland_module) else {
bail!("Entry module must be evaluatable");
};
let wasm_paths_from_root = let EntryChunkGroupResult { asset: chunk, .. } = *chunking_context
get_wasm_paths_from_root(&node_root_value, &all_output_assets).await?; .entry_chunk_group(
this.project.node_root().join("server/middleware.js".into()),
*module,
get_server_runtime_entries(
Value::new(ServerContextType::Middleware {
app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name,
}),
this.project.next_mode(),
)
.resolve_entries(*this.asset_context),
module_graph,
OutputAssets::empty(),
Value::new(AvailabilityInfo::Root),
)
.await?;
Ok(*chunk)
}
let all_assets = get_asset_paths_from_root(&node_root_value, &all_output_assets).await?; #[turbo_tasks::function]
async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?;
// Awaited later for parallelism let userland_module = self.userland_module();
let config = config.await?;
let regions = if let Some(regions) = config.regions.as_ref() { let config = parse_config_from_source(userland_module, NextRuntime::Edge).await?;
if regions.len() == 1 {
regions
.first()
.map(|region| Regions::Single(region.clone()))
} else {
Some(Regions::Multiple(regions.clone()))
}
} else {
None
};
let next_config = this.project.next_config().await?; let next_config = this.project.next_config().await?;
let has_i18n = next_config.i18n.is_some(); let has_i18n = next_config.i18n.is_some();
...@@ -220,8 +236,9 @@ impl MiddlewareEndpoint { ...@@ -220,8 +236,9 @@ impl MiddlewareEndpoint {
source.insert_str(0, base_path); source.insert_str(0, base_path);
} }
// TODO: The implementation of getMiddlewareMatchers outputs a regex here using // TODO: The implementation of getMiddlewareMatchers outputs a regex here
// path-to-regexp. Currently there is no equivalent of that so it post-processes // using path-to-regexp. Currently there is no
// equivalent of that so it post-processes
// this value to the relevant regex in manifest-loader.ts // this value to the relevant regex in manifest-loader.ts
matcher.regexp = Some(RcStr::from(source)); matcher.regexp = Some(RcStr::from(source));
...@@ -236,6 +253,66 @@ impl MiddlewareEndpoint { ...@@ -236,6 +253,66 @@ impl MiddlewareEndpoint {
}] }]
}; };
if matches!(config.runtime, NextRuntime::NodeJs) {
let chunk = self.node_chunk().to_resolved().await?;
let mut output_assets = vec![chunk];
if this.project.next_mode().await?.is_production() {
output_assets.push(ResolvedVc::upcast(
NftJsonAsset::new(*this.project, *chunk, vec![])
.to_resolved()
.await?,
));
}
let middleware_manifest_v2 = MiddlewaresManifestV2 {
middleware: [].into_iter().collect(),
..Default::default()
};
let middleware_manifest_v2 = VirtualOutputAsset::new(
this.project
.node_root()
.join("server/middleware/middleware-manifest.json".into()),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
)?))
.cell(),
),
)
.to_resolved()
.await?;
output_assets.push(ResolvedVc::upcast(middleware_manifest_v2));
Ok(Vc::cell(output_assets))
} else {
let edge_files = self.edge_files();
let mut output_assets = edge_files.owned().await?;
let node_root = this.project.node_root();
let node_root_value = node_root.await?;
let file_paths_from_root =
get_js_paths_from_root(&node_root_value, &output_assets).await?;
let all_output_assets = all_assets_from_entries(edge_files).await?;
let wasm_paths_from_root =
get_wasm_paths_from_root(&node_root_value, &all_output_assets).await?;
let all_assets =
get_asset_paths_from_root(&node_root_value, &all_output_assets).await?;
let regions = if let Some(regions) = config.regions.as_ref() {
if regions.len() == 1 {
regions
.first()
.map(|region| Regions::Single(region.clone()))
} else {
Some(Regions::Multiple(regions.clone()))
}
} else {
None
};
let edge_function_definition = EdgeFunctionDefinition { let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root, files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root), wasm: wasm_paths_to_bindings(wasm_paths_from_root),
...@@ -243,7 +320,7 @@ impl MiddlewareEndpoint { ...@@ -243,7 +320,7 @@ impl MiddlewareEndpoint {
name: "middleware".into(), name: "middleware".into(),
page: "/".into(), page: "/".into(),
regions, regions,
matchers, matchers: matchers.clone(),
env: this.project.edge_env().owned().await?, env: this.project.edge_env().owned().await?,
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
...@@ -267,6 +344,7 @@ impl MiddlewareEndpoint { ...@@ -267,6 +344,7 @@ impl MiddlewareEndpoint {
Ok(Vc::cell(output_assets)) Ok(Vc::cell(output_assets))
} }
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn userland_module(&self) -> Vc<Box<dyn Module>> { fn userland_module(&self) -> Vc<Box<dyn Module>> {
......
...@@ -843,7 +843,7 @@ impl PageEndpoint { ...@@ -843,7 +843,7 @@ impl PageEndpoint {
.process(self.source(), reference_type.clone()) .process(self.source(), reference_type.clone())
.module(); .module();
let config = parse_config_from_source(ssr_module).await?; let config = parse_config_from_source(ssr_module, NextRuntime::default()).await?;
let is_edge = matches!(config.runtime, NextRuntime::Edge); let is_edge = matches!(config.runtime, NextRuntime::Edge);
let ssr_module = if is_edge { let ssr_module = if is_edge {
......
...@@ -18,7 +18,7 @@ use next_core::{ ...@@ -18,7 +18,7 @@ use next_core::{
get_server_resolve_options_context, ServerContextType, get_server_resolve_options_context, ServerContextType,
}, },
next_telemetry::NextFeatureTelemetry, next_telemetry::NextFeatureTelemetry,
util::NextRuntime, util::{parse_config_from_source, NextRuntime},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
...@@ -55,6 +55,7 @@ use turbopack_core::{ ...@@ -55,6 +55,7 @@ use turbopack_core::{
module::Module, module::Module,
module_graph::{GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules}, module_graph::{GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules},
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
reference_type::{EntryReferenceSubType, ReferenceType},
resolve::{find_context_file, FindContextFileResult}, resolve::{find_context_file, FindContextFileResult},
source_map::OptionStringifiedSourceMap, source_map::OptionStringifiedSourceMap,
version::{ version::{
...@@ -1243,9 +1244,9 @@ impl Project { ...@@ -1243,9 +1244,9 @@ impl Project {
)); ));
} }
Ok(Vc::upcast(ModuleAssetContext::new( let edge_module_context = ModuleAssetContext::new(
TransitionOptions { TransitionOptions {
named_transitions: transitions.into_iter().collect(), named_transitions: transitions.clone().into_iter().collect(),
..Default::default() ..Default::default()
} }
.cell(), .cell(),
...@@ -1273,7 +1274,60 @@ impl Project { ...@@ -1273,7 +1274,60 @@ impl Project {
self.execution_context(), self.execution_context(),
), ),
Vc::cell("middleware".into()), Vc::cell("middleware".into()),
))) );
let middleware = self.find_middleware();
let FindContextFileResult::Found(fs_path, _) = *middleware.await? else {
return Ok(Vc::upcast(edge_module_context));
};
let source = Vc::upcast(FileSource::new(*fs_path));
let module = edge_module_context
.process(
source,
Value::new(ReferenceType::Entry(EntryReferenceSubType::Middleware)),
)
.module();
let config = parse_config_from_source(module, NextRuntime::Edge).await?;
if matches!(config.runtime, NextRuntime::NodeJs) {
let server_module_context = ModuleAssetContext::new(
TransitionOptions {
named_transitions: transitions.clone().into_iter().collect(),
..Default::default()
}
.cell(),
self.server_compile_time_info(),
get_server_module_options_context(
self.project_path(),
self.execution_context(),
Value::new(ServerContextType::Middleware {
app_dir,
ecmascript_client_reference_transition_name,
}),
self.next_mode(),
self.next_config(),
NextRuntime::NodeJs,
self.encryption_key(),
),
get_server_resolve_options_context(
self.project_path(),
Value::new(ServerContextType::Middleware {
app_dir,
ecmascript_client_reference_transition_name,
}),
self.next_mode(),
self.next_config(),
self.execution_context(),
),
Vc::cell("middleware".into()),
);
Ok(Vc::upcast(server_module_context))
} else {
Ok(Vc::upcast(edge_module_context))
}
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -1300,6 +1354,7 @@ impl Project { ...@@ -1300,6 +1354,7 @@ impl Project {
Ok(Vc::upcast(MiddlewareEndpoint::new( Ok(Vc::upcast(MiddlewareEndpoint::new(
self, self,
self.await?.build_id.clone(),
middleware_asset_context, middleware_asset_context,
source, source,
app_dir.as_deref().copied(), app_dir.as_deref().copied(),
......
...@@ -270,10 +270,7 @@ pub async fn get_server_resolve_options_context( ...@@ -270,10 +270,7 @@ pub async fn get_server_resolve_options_context(
ResolvedVc::upcast(next_external_plugin), ResolvedVc::upcast(next_external_plugin),
] ]
} }
ServerContextType::Middleware { .. } => { ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
vec![ResolvedVc::upcast(next_node_shared_runtime_plugin)]
}
ServerContextType::Instrumentation { .. } => {
vec![ vec![
ResolvedVc::upcast(next_node_shared_runtime_plugin), ResolvedVc::upcast(next_node_shared_runtime_plugin),
ResolvedVc::upcast(server_external_packages_plugin), ResolvedVc::upcast(server_external_packages_plugin),
......
...@@ -427,6 +427,7 @@ async fn parse_route_matcher_from_js_value( ...@@ -427,6 +427,7 @@ async fn parse_route_matcher_from_js_value(
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn parse_config_from_source( pub async fn parse_config_from_source(
module: ResolvedVc<Box<dyn Module>>, module: ResolvedVc<Box<dyn Module>>,
default_runtime: NextRuntime,
) -> Result<Vc<NextSourceConfig>> { ) -> Result<Vc<NextSourceConfig>> {
if let Some(ecmascript_asset) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptParsable>>(module) if let Some(ecmascript_asset) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptParsable>>(module)
{ {
...@@ -456,7 +457,11 @@ pub async fn parse_config_from_source( ...@@ -456,7 +457,11 @@ pub async fn parse_config_from_source(
return WrapFuture::new( return WrapFuture::new(
async { async {
let value = eval_context.eval(init); let value = eval_context.eval(init);
Ok(parse_config_from_js_value(*module, &value) Ok(parse_config_from_js_value(
*module,
&value,
default_runtime,
)
.await? .await?
.cell()) .cell())
}, },
...@@ -537,14 +542,23 @@ pub async fn parse_config_from_source( ...@@ -537,14 +542,23 @@ pub async fn parse_config_from_source(
} }
} }
} }
Ok(Default::default()) let config = NextSourceConfig {
runtime: default_runtime,
..Default::default()
};
Ok(config.cell())
} }
async fn parse_config_from_js_value( async fn parse_config_from_js_value(
module: Vc<Box<dyn Module>>, module: Vc<Box<dyn Module>>,
value: &JsValue, value: &JsValue,
default_runtime: NextRuntime,
) -> Result<NextSourceConfig> { ) -> Result<NextSourceConfig> {
let mut config = NextSourceConfig::default(); let mut config = NextSourceConfig {
runtime: default_runtime,
..Default::default()
};
if let JsValue::Object { parts, .. } = value { if let JsValue::Object { parts, .. } = value {
for part in parts { for part in parts {
......
...@@ -80,6 +80,7 @@ import { ...@@ -80,6 +80,7 @@ import {
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE, UNDERSCORE_NOT_FOUND_ROUTE,
DYNAMIC_CSS_MANIFEST, DYNAMIC_CSS_MANIFEST,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { import {
getSortedRoutes, getSortedRoutes,
...@@ -2348,6 +2349,18 @@ export default async function build( ...@@ -2348,6 +2349,18 @@ export default async function build(
}, },
], ],
} }
if (turboNextBuild) {
await writeManifest(
path.join(
distDir,
'static',
buildId,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST
),
functionsConfigManifest.functions['/_middleware'].matchers || []
)
}
} }
} }
......
...@@ -692,12 +692,14 @@ export async function handleEntrypoints({ ...@@ -692,12 +692,14 @@ export async function handleEntrypoints({
dev.hooks.handleWrittenEndpoint(key, writtenEndpoint) dev.hooks.handleWrittenEndpoint(key, writtenEndpoint)
processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors) processIssues(currentEntryIssues, key, writtenEndpoint, false, logErrors)
await manifestLoader.loadMiddlewareManifest('middleware', 'middleware') await manifestLoader.loadMiddlewareManifest('middleware', 'middleware')
if (dev) { const middlewareConfig =
manifestLoader.getMiddlewareManifest(key)?.middleware['/']
if (dev && middlewareConfig) {
dev.serverFields.middleware = { dev.serverFields.middleware = {
match: null as any, match: null as any,
page: '/', page: '/',
matchers: matchers: middlewareConfig.matchers,
manifestLoader.getMiddlewareManifest(key)?.middleware['/'].matchers,
} }
} }
} }
......
...@@ -49,6 +49,7 @@ import { ...@@ -49,6 +49,7 @@ import {
DEV_CLIENT_PAGES_MANIFEST, DEV_CLIENT_PAGES_MANIFEST,
DEV_CLIENT_MIDDLEWARE_MANIFEST, DEV_CLIENT_MIDDLEWARE_MANIFEST,
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher' import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'
...@@ -902,6 +903,9 @@ async function startWatcher(opts: SetupOpts) { ...@@ -902,6 +903,9 @@ async function startWatcher(opts: SetupOpts) {
const devMiddlewareManifestPath = `/_next/${CLIENT_STATIC_FILES_PATH}/development/${DEV_CLIENT_MIDDLEWARE_MANIFEST}` const devMiddlewareManifestPath = `/_next/${CLIENT_STATIC_FILES_PATH}/development/${DEV_CLIENT_MIDDLEWARE_MANIFEST}`
opts.fsChecker.devVirtualFsItems.add(devMiddlewareManifestPath) opts.fsChecker.devVirtualFsItems.add(devMiddlewareManifestPath)
const devTurbopackMiddlewareManifestPath = `/_next/${CLIENT_STATIC_FILES_PATH}/development/${TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST}`
opts.fsChecker.devVirtualFsItems.add(devTurbopackMiddlewareManifestPath)
async function requestHandler(req: IncomingMessage, res: ServerResponse) { async function requestHandler(req: IncomingMessage, res: ServerResponse) {
const parsedUrl = url.parse(req.url || '/') const parsedUrl = url.parse(req.url || '/')
...@@ -918,7 +922,10 @@ async function startWatcher(opts: SetupOpts) { ...@@ -918,7 +922,10 @@ async function startWatcher(opts: SetupOpts) {
return { finished: true } return { finished: true }
} }
if (parsedUrl.pathname?.includes(devMiddlewareManifestPath)) { if (
parsedUrl.pathname?.includes(devMiddlewareManifestPath) ||
parsedUrl.pathname?.includes(devTurbopackMiddlewareManifestPath)
) {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(serverFields.middleware?.matchers || [])) res.end(JSON.stringify(serverFields.middleware?.matchers || []))
......
import { NextResponse } from 'next/server'
export default function middleware(request) {
const res = NextResponse.rewrite(new URL('/', request.url))
res.headers.set('X-From-Middleware', 'true')
return res
}
export const config = {
runtime: 'nodejs',
matcher: [
{ source: '/source-match' },
{
source: '/has-match-1',
has: [
{
type: 'header',
key: 'x-my-header',
value: '(?<myHeader>.*)',
},
],
},
{
source: '/has-match-2',
has: [
{
type: 'query',
key: 'my-query',
},
],
},
{
source: '/has-match-3',
has: [
{
type: 'cookie',
key: 'loggedIn',
value: '(?<loggedIn>true)',
},
],
},
{
source: '/has-match-4',
has: [
{
type: 'host',
value: 'example.com',
},
],
},
{
source: '/has-match-5',
has: [
{
type: 'header',
key: 'hasParam',
value: 'with-params',
},
],
},
{
source: '/missing-match-1',
missing: [
{
type: 'header',
key: 'hello',
value: '(.*)',
},
],
},
{
source: '/missing-match-2',
missing: [
{
type: 'query',
key: 'test',
value: 'value',
},
],
},
{
source:
'/((?!api|monitoring|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|manifest|icon|source-match|has-match-1|has-match-2|has-match-3|has-match-4|has-match-5|missing-match-1|missing-match-2|routes).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
}
module.exports = {
experimental: {
nodeMiddleware: true,
},
}
...@@ -13,9 +13,20 @@ const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy' ...@@ -13,9 +13,20 @@ const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy'
describe('Middleware custom matchers', () => { describe('Middleware custom matchers', () => {
let next: NextInstance let next: NextInstance
if ((global as any).isNextDeploy && process.env.TEST_NODE_MIDDLEWARE) {
return it('should skip deploy for now', () => {})
}
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: new FileRef(join(__dirname, '../app')), files: new FileRef(join(__dirname, '../app')),
overrideFiles: process.env.TEST_NODE_MIDDLEWARE
? {
'middleware.js': new FileRef(
join(__dirname, '../app/middleware-node.js')
),
}
: {},
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
......
process.env.TEST_NODE_MIDDLEWARE = 'true'
require('./index.test')
process.env.TEST_NODE_MIDDLEWARE = 'true' process.env.TEST_NODE_MIDDLEWARE = 'true'
if (process.env.TURBOPACK) { require('./index.test')
it('should skip', () => {})
} else {
require('./index.test')
}
...@@ -111,6 +111,9 @@ describe('Edge runtime code with imports', () => { ...@@ -111,6 +111,9 @@ describe('Edge runtime code with imports', () => {
stderr: true, stderr: true,
}) })
expect(stderr).toContain(getUnsupportedModuleWarning(moduleName)) expect(stderr).toContain(getUnsupportedModuleWarning(moduleName))
// TODO: should this be failing build or not in turbopack
if (!process.env.TURBOPACK) {
context.app = await nextStart( context.app = await nextStart(
context.appDir, context.appDir,
context.appPort, context.appPort,
...@@ -119,6 +122,7 @@ describe('Edge runtime code with imports', () => { ...@@ -119,6 +122,7 @@ describe('Edge runtime code with imports', () => {
const res = await fetchViaHTTP(context.appPort, url) const res = await fetchViaHTTP(context.appPort, url)
expect(res.status).toBe(500) expect(res.status).toBe(500)
expectUnsupportedModuleProdError(moduleName) expectUnsupportedModuleProdError(moduleName)
}
}) })
} }
) )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment