Skip to content

fix: handle absolute rewrite URLs #1325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion demos/middleware/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export default function Home() {
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>

<p><Link href="/shows/rewriteme">Rewrite me</Link></p>
<p><Link href="/shows/rewriteme">Rewrite URL</Link></p>
<p><Link href="/shows/rewrite-absolute">Rewrite to absolute URL</Link></p>
<p><Link href="/shows/rewrite-external">Rewrite to external URL</Link></p>
</main>
</div>
)
Expand Down
8 changes: 8 additions & 0 deletions demos/middleware/pages/shows/rewrite-absolute/_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { NextResponse } from 'next/server'
import { NextFetchEvent, NextRequest } from 'next/server'

export function middleware(req: NextRequest, ev: NextFetchEvent) {
const res = NextResponse.rewrite(new URL('/shows/100', req.url))
res.headers.set('x-modified-in-rewrite', 'true')
return res
}
9 changes: 9 additions & 0 deletions demos/middleware/pages/shows/rewrite-absolute/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const Show = () => {
return (
<div>
<p>This should have been rewritten</p>
</div>
)
}

export default Show
8 changes: 8 additions & 0 deletions demos/middleware/pages/shows/rewrite-external/_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { NextResponse } from 'next/server'
import { NextFetchEvent, NextRequest } from 'next/server'

export function middleware(req: NextRequest, ev: NextFetchEvent) {
const res = NextResponse.rewrite('http://example.com/')
res.headers.set('x-modified-in-rewrite', 'true')
return res
}
9 changes: 9 additions & 0 deletions demos/middleware/pages/shows/rewrite-external/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const Show = () => {
return (
<div>
<p>This should have been rewritten</p>
</div>
)
}

export default Show
24 changes: 23 additions & 1 deletion plugin/src/templates/edge/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@ export interface FetchEventResult {
waitUntil: Promise<any>
}

/**
* This is how Next handles rewritten URLs.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[dust] Might be handy to include the same link that was provided in the pull request summary here so it makes it easier to folks to find the relevant code that's being referred to here

*/
export function relativizeURL(url: string | string, base: string | URL) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[boulder] Is it a mistake that the url parameter's type is string | string or was it meant to be string | URL?

Suggested change
export function relativizeURL(url: string | string, base: string | URL) {
export function relativizeURL(url: string | URL, base: string | URL) {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, missed this before adding automerge! That's copied directly from the Next.js source and certainly looks like a mistake!

const baseURL = typeof base === 'string' ? new URL(base) : base
const relative = new URL(url, base)
const origin = `${baseURL.protocol}//${baseURL.host}`
return `${relative.protocol}//${relative.host}` === origin
? relative.toString().replace(origin, '')
: relative.toString()
}


export const addMiddlewareHeaders = async (
originResponse: Promise<Response> | Response,
middlewareResponse: Response,
Expand All @@ -14,7 +27,8 @@ export const addMiddlewareHeaders = async (
return originResponse
}
// We need to await the response to get the origin headers, then we can add the ones from middleware.
const response = await originResponse
const res = await originResponse
const response = new Response(res.body, res)
middlewareResponse.headers.forEach((value, key) => {
response.headers.set(key, value)
})
Expand All @@ -33,6 +47,14 @@ export const buildResponse = async ({
request.headers.set('x-nf-next-middleware', 'skip')
const rewrite = res.headers.get('x-middleware-rewrite')
if (rewrite) {
const rewriteUrl = new URL(rewrite, request.url)
const baseUrl = new URL(request.url)
if(rewriteUrl.hostname !== baseUrl.hostname) {
// Netlify Edge Functions don't support proxying to external domains, but Next middleware does
const proxied = fetch(new Request(rewriteUrl.toString(), request))
return addMiddlewareHeaders(proxied, res)
}
res.headers.set('x-middleware-rewrite', relativizeURL(rewrite, request.url))
return addMiddlewareHeaders(context.rewrite(rewrite), res)
}
if (res.headers.get('x-middleware-next') === '1') {
Expand Down