-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathnext-dev.js
94 lines (81 loc) · 3.04 KB
/
next-dev.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { NextRequest } from 'https://esm.sh/v91/[email protected]/deno/dist/server/web/spec-extension/request.js'
import { NextResponse } from 'https://esm.sh/v91/[email protected]/deno/dist/server/web/spec-extension/response.js'
import { fromFileUrl } from 'https://deno.land/[email protected]/path/mod.ts'
import { buildResponse } from '../edge-shared/utils.ts'
globalThis.NFRequestContextMap ||= new Map()
globalThis.__dirname = fromFileUrl(new URL('./', import.meta.url)).slice(0, -1)
globalThis.process ||= { env: Deno.env.toObject() }
// Next.js uses this extension to the Headers API implemented by Cloudflare workerd
if (!('getAll' in Headers.prototype)) {
Headers.prototype.getAll = function getAll(name) {
name = name.toLowerCase()
if (name !== 'set-cookie') {
throw new Error('Headers.getAll is only supported for Set-Cookie')
}
return [...this.entries()].filter(([key]) => key === name).map(([, value]) => value)
}
}
let idx = 0
const handler = async (req, context) => {
if (!Deno.env.get('NETLIFY_DEV')) {
// Only run in dev
return
}
let middleware
// Dynamic imports and FS operations aren't allowed when deployed,
// but that's fine because this is only ever used locally.
// We don't want to just try importing and use that to test,
// because that would also throw if there's an error in the middleware,
// which we would want to surface not ignore.
try {
// We need to cache-bust the import because otherwise it will claim it
// doesn't exist if the user creates it after the server starts
const nextMiddleware = await import(`../../middleware.js#${++idx}`)
middleware = nextMiddleware.middleware
} catch (importError) {
if (importError.code === 'ERR_MODULE_NOT_FOUND' && importError.message.includes(`middleware.js`)) {
// No middleware, so we silently return
return
}
throw importError
}
// This is the format expected by Next.js along with the timezone which we support.
const geo = {
country: context.geo.country?.code,
region: context.geo.subdivision?.code,
city: context.geo.city,
latitude: context.geo.latitude?.toString(),
longitude: context.geo.longitude?.toString(),
timezone: context.geo.timezone,
}
// A default request id is fine locally
const requestId = req.headers.get('x-nf-request-id') || 'request-id'
globalThis.NFRequestContextMap.set(requestId, {
request: req,
context,
})
const request = {
headers: Object.fromEntries(req.headers.entries()),
geo,
method: req.method,
ip: context.ip,
body: req.body || undefined,
}
const nextRequest = new NextRequest(req, request)
try {
const response = await middleware(nextRequest)
return buildResponse({
result: { response: response || NextResponse.next(), waitUntil: Promise.resolve() },
request: req,
context,
})
} catch (error) {
console.error(error)
return new Response(error.message, { status: 500 })
} finally {
if (requestId) {
globalThis.NFRequestContextMap.delete(requestId)
}
}
}
export default handler