Skip to content

Commit befe21a

Browse files
committed
more
1 parent d055699 commit befe21a

File tree

6 files changed

+68
-31
lines changed

6 files changed

+68
-31
lines changed

edge-runtime/lib/next-request.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import type { Context } from '@netlify/edge-functions'
22

33
import type { RequestData } from './types'
44

5-
export const buildNextRequest = (request: Request): RequestData => {
5+
export const buildNextRequest = (
6+
request: Request,
7+
nextConfig: RequestData['nextConfig'],
8+
): RequestData => {
69
const { url, method, body, headers } = request
710

811
// we don't really use it but Next.js expects a signal
@@ -11,12 +14,7 @@ export const buildNextRequest = (request: Request): RequestData => {
1114
return {
1215
headers: Object.fromEntries(headers.entries()),
1316
method,
14-
// nextConfig?: {
15-
// basePath?: string;
16-
// i18n?: I18NConfig | null;
17-
// trailingSlash?: boolean;
18-
// experimental?: Pick<ExperimentalConfig, 'cacheLife' | 'authInterrupts' | 'clientParamParsingOrigins'>;
19-
// };
17+
nextConfig,
2018
// page?: {
2119
// name?: string;
2220
// params?: {

edge-runtime/middleware.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { InternalHeaders } from './lib/headers.ts'
44
import { logger, LogLevel } from './lib/logging.ts'
55
import { buildNextRequest } from './lib/next-request.ts'
6-
import type { NextHandler } from './lib/types.ts'
6+
import type { NextHandler, RequestData } from './lib/types.ts'
77
// import { buildResponse } from './lib/response.ts'
88

99
/**
@@ -15,7 +15,11 @@ import type { NextHandler } from './lib/types.ts'
1515
* @param context Netlify-specific context object
1616
* @param nextHandler Next.js middleware handler
1717
*/
18-
export async function handleMiddleware(request: Request, nextHandler: NextHandler) {
18+
export async function handleMiddleware(
19+
request: Request,
20+
nextHandler: NextHandler,
21+
nextConfig: RequestData['nextConfig'],
22+
) {
1923
const url = new URL(request.url)
2024

2125
const reqLogger = logger
@@ -25,7 +29,7 @@ export async function handleMiddleware(request: Request, nextHandler: NextHandle
2529
.withFields({ url_path: url.pathname })
2630
.withRequestID(request.headers.get(InternalHeaders.NFRequestID))
2731

28-
const nextRequest = buildNextRequest(request)
32+
const nextRequest = buildNextRequest(request, nextConfig)
2933
try {
3034
const result = await nextHandler({ request: nextRequest })
3135

src/adapter/adapter.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const adapter: NextAdapter = {
3333
await writeFile('./onBuildComplete.json', JSON.stringify(nextAdapterContext, null, 2))
3434
// debugger
3535

36-
const netlifyAdapterContext = createNetlifyAdapterContext(nextAdapterContext)
36+
const netlifyAdapterContext = createNetlifyAdapterContext()
3737

3838
await onBuildCompleteForImageCDN(nextAdapterContext, netlifyAdapterContext)
3939
await onBuildCompleteForMiddleware(nextAdapterContext, netlifyAdapterContext)

src/adapter/build/middleware.ts

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
import { cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'
22
import { dirname, join, parse, relative } from 'node:path/posix'
33

4-
import type { IntegrationsConfig } from '@netlify/edge-functions'
54
import { glob } from 'fast-glob'
6-
import { pathToRegexp } from 'path-to-regexp'
5+
6+
import type { RequestData } from '../../../edge-runtime/lib/types.ts'
7+
8+
// import type { IntegrationsConfig } from '@netlify/edge-functions'
9+
10+
// import { pathToRegexp } from 'path-to-regexp'
711

812
import {
9-
DISPLAY_NAME_MIDDLEWARE,
10-
GENERATOR,
13+
// DISPLAY_NAME_MIDDLEWARE,
14+
// GENERATOR,
1115
NETLIFY_FRAMEWORKS_API_EDGE_FUNCTIONS,
1216
PLUGIN_DIR,
1317
} from './constants.js'
@@ -152,6 +156,18 @@ const writeHandlerFile = async (
152156
// Netlify Edge Functions and the Next.js edge runtime.
153157
await copyRuntime(MIDDLEWARE_FUNCTION_DIR)
154158

159+
const nextConfigForMiddleware: RequestData['nextConfig'] = {
160+
basePath: nextConfig.basePath,
161+
i18n: nextConfig.i18n,
162+
trailingSlash: nextConfig.trailingSlash,
163+
experimental: {
164+
// Include any experimental config that might affect middleware behavior
165+
cacheLife: nextConfig.experimental?.cacheLife,
166+
authInterrupts: nextConfig.experimental?.authInterrupts,
167+
clientParamParsingOrigins: nextConfig.experimental?.clientParamParsingOrigins,
168+
},
169+
}
170+
155171
// Writing a file with the matchers that should trigger this function. We'll
156172
// read this file from the function at runtime.
157173
// await writeFile(
@@ -196,7 +212,9 @@ const writeHandlerFile = async (
196212
import { handleMiddleware } from './edge-runtime/middleware.ts';
197213
import handler from './concatenated-file.js';
198214
199-
export default (req) => handleMiddleware(req, handler);
215+
const nextConfig = ${JSON.stringify(nextConfigForMiddleware)}
216+
217+
export default (req) => handleMiddleware(req, handler, nextConfig);
200218
`,
201219
)
202220
}

src/adapter/build/routing.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export async function generateRoutingRules(
6262
nextAdapterContext: OnBuildCompleteContext,
6363
netlifyAdapterContext: NetlifyAdapterContext,
6464
) {
65-
const escapedBuildId = escapeStringRegexp(nextAdapterContext.buildId)
65+
// const escapedBuildId = escapeStringRegexp(nextAdapterContext.buildId)
6666

6767
const hasMiddleware = Boolean(nextAdapterContext.outputs.middleware)
6868
const hasPages =
@@ -72,7 +72,7 @@ export async function generateRoutingRules(
7272
nextAdapterContext.outputs.appPages.length !== 0 ||
7373
nextAdapterContext.outputs.appRoutes.length !== 0
7474
const shouldDenormalizeJsonDataForMiddleware =
75-
hasMiddleware && hasPages && nextAdapterContext.config.skipMiddlewareUrlNormalize
75+
hasMiddleware && hasPages && !nextAdapterContext.config.skipMiddlewareUrlNormalize
7676

7777
// group redirects by priority, as it impact ordering of routing rules
7878
const priorityRedirects: RoutingRuleApply[] = []
@@ -128,7 +128,7 @@ export async function generateRoutingRules(
128128
{
129129
description: 'Normalize _next/data',
130130
match: {
131-
path: `^${nextAdapterContext.config.basePath}/_next/data/${escapedBuildId}/(.*)\\.json`,
131+
path: `^${nextAdapterContext.config.basePath}/_next/data/${nextAdapterContext.buildId}/(.*)\\.json`,
132132
has: [
133133
{
134134
type: 'header',
@@ -140,6 +140,7 @@ export async function generateRoutingRules(
140140
type: 'rewrite',
141141
destination: `${nextAdapterContext.config.basePath}/$1${nextAdapterContext.config.trailingSlash ? '/' : ''}`,
142142
},
143+
continue: true,
143144
},
144145
{
145146
description: 'Fix _next/data index normalization',
@@ -156,6 +157,7 @@ export async function generateRoutingRules(
156157
type: 'rewrite',
157158
destination: `${nextAdapterContext.config.basePath}/`,
158159
},
160+
continue: true,
159161
},
160162
]
161163
: []
@@ -177,6 +179,7 @@ export async function generateRoutingRules(
177179
type: 'rewrite',
178180
destination: `${nextAdapterContext.config.basePath}/index`,
179181
},
182+
continue: true,
180183
},
181184
{
182185
description: 'Denormalize _next/data',
@@ -193,6 +196,7 @@ export async function generateRoutingRules(
193196
type: 'rewrite',
194197
destination: `${nextAdapterContext.config.basePath}/_next/data/${nextAdapterContext.buildId}/$1.json`,
195198
},
199+
continue: true,
196200
},
197201
]
198202
: []
@@ -312,23 +316,22 @@ export async function generateRoutingRules(
312316

313317
// server actions name meta routes
314318

315-
...denormalizeNextData, // originally: // if skip middleware url normalize we denormalize _next/data if middleware + pages
316-
317319
...(hasMiddleware
318320
? [
319321
{
320322
// originally: middleware route
321323
description: 'Middleware',
322324
// match: {
325+
// path: 'test',
326+
// },
327+
// match: {
323328
// path: 'wat',
324329
// },
325330
apply: { type: 'middleware' },
326331
} as const,
327332
]
328333
: []),
329334

330-
...normalizeNextData, // originally: // if skip middleware url normalize we normalize _next/data if middleware + pages
331-
332335
// ...convertedRewrites.beforeFiles,
333336

334337
// add 404 handling if /404 or locale variants are requested literally
@@ -487,6 +490,7 @@ export async function generateRoutingRules(
487490
routingPhase: 'rewrite',
488491
},
489492

493+
...denormalizeNextData,
490494
// denormalize _next/data if middleware + pages
491495

492496
// apply _next/data routes (including static ones if middleware + pages)
@@ -508,7 +512,7 @@ export async function generateRoutingRules(
508512
'/',
509513
nextAdapterContext.config.basePath,
510514
'/_next/data/',
511-
escapedBuildId,
515+
nextAdapterContext.buildId,
512516
'/(.*).json',
513517
)}`,
514518
},
@@ -529,7 +533,7 @@ export async function generateRoutingRules(
529533
'/',
530534
nextAdapterContext.config.basePath,
531535
'/_next/data/',
532-
escapedBuildId,
536+
nextAdapterContext.buildId,
533537
'/(.*).json',
534538
)}`,
535539
},

src/adapter/run/routing.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -142,17 +142,18 @@ async function match(
142142
let currentRequest = request
143143
let maybeResponse: MaybeResponse = initialResponse
144144

145-
const currentURL = new URL(currentRequest.url)
146-
let { pathname } = currentURL
147-
148145
return tracer.withActiveSpan(spanName, async (span) => {
149146
for (const rule of routingRules) {
147+
const currentURL = new URL(currentRequest.url)
148+
const { pathname } = currentURL
149+
150150
const desc = rule.description ?? JSON.stringify(rule)
151151
// eslint-disable-next-line no-loop-func
152152
const result = await tracer.withActiveSpan(desc, async (span) => {
153-
log('Evaluating rule:', desc)
153+
log('Evaluating rule:', desc, pathname)
154154

155155
let matched = false
156+
let shouldContinueOnMatch = rule.continue ?? false
156157

157158
if ('type' in rule) {
158159
if (rule.type === 'static-asset-or-function') {
@@ -172,7 +173,7 @@ async function match(
172173
new URL(staticAlias, currentRequest.url),
173174
currentRequest,
174175
)
175-
pathname = staticAlias
176+
// pathname = staticAlias
176177
}
177178
}
178179

@@ -213,6 +214,7 @@ async function match(
213214
}
214215
} else {
215216
span.setStatus({ code: SpanStatusCode.ERROR, message: 'Miss' })
217+
// log('Path did not match regex', rule.match.path, pathname)
216218
return
217219
}
218220
}
@@ -224,10 +226,18 @@ async function match(
224226
if (typeof condition.value === 'undefined') {
225227
if (!currentRequest.headers.has(condition.key)) {
226228
hasAllMatch = false
229+
// log('request header does not exist', {
230+
// key: condition.key,
231+
// })
227232
break
228233
}
229234
} else if (currentRequest.headers.get(condition.key) !== condition.value) {
230235
hasAllMatch = false
236+
// log('request header not the same', {
237+
// key: condition.key,
238+
// match: condition.value,
239+
// actual: currentRequest.headers.get(condition.key),
240+
// })
231241
break
232242
}
233243
}
@@ -381,12 +391,15 @@ async function match(
381391
new URL(rewriteUrl, currentRequest.url),
382392
currentRequest,
383393
)
394+
shouldContinueOnMatch = true
384395
} else if (nextRedirect) {
396+
shouldContinueOnMatch = true
385397
// just continue
386398
// } else if (redirect) {
387399
// relativizeURL(redirect, currentRequest.url)
388400
} else if (isNext) {
389401
// just continue
402+
shouldContinueOnMatch = true
390403
} else {
391404
// this includes redirect case
392405
maybeResponse = {
@@ -458,7 +471,7 @@ async function match(
458471
}
459472
}
460473

461-
if (matched && !rule.continue) {
474+
if (matched && !shouldContinueOnMatch) {
462475
// once hit a match short circuit, unless we should continue
463476
return { maybeResponse, currentRequest }
464477
}

0 commit comments

Comments
 (0)