-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathnext-dev.js
87 lines (76 loc) · 2.52 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
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 './utils.ts'
globalThis.NFRequestContextMap ||= new Map()
globalThis.__dirname = fromFileUrl(new URL('./', import.meta.url)).slice(0, -1)
// Check if a file exists, given a relative path
const exists = async (relativePath) => {
const path = fromFileUrl(new URL(relativePath, import.meta.url))
try {
await Deno.stat(path)
return true
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false
}
throw error
}
}
const handler = async (req, context) => {
// Uncomment when CLI update lands
// 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.
if (await exists('../../middleware.js')) {
// These will be user code
const nextMiddleware = await import('../../middleware.js')
middleware = nextMiddleware.middleware
} else {
// No middleware, so we silently return
return
}
// This is the format expected by Next.js
const geo = {
country: context.geo.country?.code,
region: context.geo.subdivision?.code,
city: context.geo.city,
}
// 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