Skip to content

Commit d66e08e

Browse files
committed
feat: add request header support
1 parent ba284d9 commit d66e08e

File tree

4 files changed

+19
-7
lines changed

4 files changed

+19
-7
lines changed

demos/middleware/middleware.ts

+12
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,16 @@ import type { ElementHandlers } from './html_rewriter'
88
class NetlifyResponse {
99
static async next(request: NextRequest): Promise<NetlifyNextResponse> {
1010
const context = (request.geo as any).__nf_context
11+
const originalRequest: Request = (request.geo as any).__nf_request
12+
1113
if (!context) {
1214
throw new Error('NetlifyResponse can only be used with Netlify Edge Functions')
1315
}
16+
17+
request.headers.forEach((value, key) => {
18+
originalRequest.headers.set(key, value)
19+
})
20+
1421
const response: Response = await context.next()
1522
return new NetlifyNextResponse(response)
1623
}
@@ -88,6 +95,11 @@ export async function middleware(request: NextRequest) {
8895
return res
8996
}
9097

98+
if (pathname.startsWith('/api/hello')) {
99+
request.headers.set('x-hello', 'world')
100+
return NetlifyResponse.next(request)
101+
}
102+
91103
if (pathname.startsWith('/cookies')) {
92104
response = NextResponse.next()
93105
response.cookies.set('netlifyCookie', 'true')

demos/middleware/pages/api/hello.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
22

33
export default function handler(req, res) {
4-
res.status(200).json({ name: 'John Doe' })
4+
res.status(200).json({ name: 'John Doe', headers: req.headers })
55
}

plugin/src/templates/edge/runtime.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,18 @@ const handler = async (req: Request, context: Context) => {
4545
}
4646

4747
// The geo object is passed through to the middleware unchanged
48-
// so we're smuggling the Netlify context object inside it
48+
// so we're smuggling the Request and Netlify context object inside it
4949

5050
Object.defineProperty(geo, '__nf_context', {
5151
value: context,
5252
enumerable: false,
5353
})
5454

55+
Object.defineProperty(geo, '__nf_request', {
56+
value: req,
57+
enumerable: false,
58+
})
59+
5560
const request: RequestData = {
5661
headers: Object.fromEntries(req.headers.entries()),
5762
geo,

plugin/src/templates/edge/utils.ts

-5
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,6 @@ export const buildResponse = async ({
9999
}
100100
const res = new Response(result.response.body, result.response)
101101
request.headers.set('x-nf-next-middleware', 'skip')
102-
res.headers.forEach((value, key) => {
103-
if (key.startsWith('x-request-header-')) {
104-
request.headers.set(key.slice(17), value)
105-
}
106-
})
107102

108103
const rewrite = res.headers.get('x-middleware-rewrite')
109104
if (rewrite) {

0 commit comments

Comments
 (0)