-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathmiddleware.ts
70 lines (60 loc) · 2.34 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import type { Context } from '@netlify/edge-functions'
import matchers from './matchers.json' with { type: 'json' }
import nextConfig from './next.config.json' with { type: 'json' }
import { InternalHeaders } from './lib/headers.ts'
import { logger, LogLevel } from './lib/logging.ts'
import { buildNextRequest, RequestData } from './lib/next-request.ts'
import { buildResponse, FetchEventResult } from './lib/response.ts'
import {
getMiddlewareRouteMatcher,
searchParamsToUrlQuery,
type MiddlewareRouteMatch,
} from './lib/routing.ts'
type NextHandler = (params: { request: RequestData }) => Promise<FetchEventResult>
const matchesMiddleware: MiddlewareRouteMatch = getMiddlewareRouteMatcher(matchers || [])
/**
* Runs a Next.js middleware as a Netlify Edge Function. It translates a web
* platform Request into a NextRequest instance on the way in, and translates
* a NextResponse into a web platform Response on the way out.
*
* @param request Incoming request
* @param context Netlify-specific context object
* @param nextHandler Next.js middleware handler
*/
export async function handleMiddleware(
request: Request,
context: Context,
nextHandler: NextHandler,
) {
const nextRequest = buildNextRequest(request, context, nextConfig)
const url = new URL(request.url)
const reqLogger = logger
.withLogLevel(
request.headers.has(InternalHeaders.NFDebugLogging) ? LogLevel.Debug : LogLevel.Log,
)
.withFields({ url_path: url.pathname })
.withRequestID(request.headers.get(InternalHeaders.NFRequestID))
// While we have already checked the path when mapping to the edge function,
// Next.js supports extra rules that we need to check here too, because we
// might be running an edge function for a path we should not. If we find
// that's the case, short-circuit the execution.
if (!matchesMiddleware(url.pathname, request, searchParamsToUrlQuery(url.searchParams))) {
reqLogger.debug('Aborting middleware due to runtime rules')
return
}
try {
const result = await nextHandler({ request: nextRequest })
const response = await buildResponse({
context,
logger: reqLogger,
request,
result,
requestLocale: nextRequest.detectedLocale,
nextConfig,
})
return response
} catch (error) {
console.error(error)
return new Response(error.message, { status: 500 })
}
}