forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Enforce absolute URLs in Edge Functions runtime (vercel#33410)
We currently have inconsistencies when working with URLs in the Edge Functions runtime, this PR addresses them introducing a warning for inconsistent usage that will break in the future. Here is the reasoning. ### The Browser When we are in a browser environment there is a fixed location stored at `globalThis.location`. Then, if one tries to build a request with a relative URL it will work using that location global hostname as _base_ to construct its URL. For example: ```typescript // https://nextjs.org new Request('/test').url; // https://nextjs.org/test Response.redirect('/test').headers.get('Location'); // https://nextjs.org/test ``` However, if we attempt to run the same code from `about:blank` it would not work because the global to use as a base `String(globalThis.location)` is not a valid URL. Therefore a call to `Response.redirect('/test')` or `new Response('/test')` would fail. ### Edge Functions Runtime In Next.js Edge Functions runtime the situation is slightly different from a browser. Say that we have a root middleware (`pages/_middleware`) that gets invoked for every page. In the middleware file we expose the handler function and also define a global variable that we mutate on every request: ```typescript // pages/_middleware let count = 0; export function middleware(req: NextRequest) { console.log(req.url); count += 1; } ``` Currently we cache the module scope in the runtime so subsequent invocations would hold the same globals and the module would not be evaluated again. This would make the counter to increment for each request that the middleware handles. It is for this reason that we **can't have a global location** that changes across different invocations. Each invocation of the same function uses the same global which also holds primitives like `URL` or `Request` so changing an hypothetical `globalThis.location` per request would affect concurrent requests being handled. Then, it is not possible to use relative URLs in the same way the browser does because we don't have a global to rely on to use its host to compose a URL from a relative path. ### Why it works today We are **not** validating what is provided to, for example, `NextResponse.rewrite()` nor `NextResponse.redirect()`. We simply create a `Response` instance that adds the corresponding header for the rewrite or the redirect. Then it is **the consumer** the one that composes the final destination based on the request. Theoretically you can pass any value and it would fail on redirect but won't validate the input. Of course this is inconsistent because it doesn't make sense that `NextResponse.rewrite('/test')` works but `fetch(new NextRequest('/test'))` does not. Also we should validate what is provided. Finally, we want to be consistent with the way a browser behaves so `new Request('/test')` _should_ not work if there is no global location which we lack. ### What this PR does We will have to deprecate the usage of relative URLs in the previously mentioned scenarios. In preparation for it, this PR adds a validation function in those places where it will break in the future, printing a warning with a link that points to a Next.js page with an explanation of the issue and ways to fix it. Although middleware changes are not covered by semver, we will roll this for some time to make people aware that this change is coming. Then after a reasonable period of time we can remove the warning and make the code fail when using relative URLs in the previously exposed scenarios.
- Loading branch information
1 parent
e970301
commit 1305ee4
Showing
15 changed files
with
206 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# Middleware Relative URLs | ||
|
||
#### Why This Error Occurred | ||
|
||
You are using a Middleware function that uses `Response.redirect(url)`, `NextResponse.redirect(url)` or `NextResponse.rewrite(url)` where `url` is a relative or an invalid URL. Currently this will work, but building a request with `new Request(url)` or running `fetch(url)` when `url` is a relative URL will **not** work. For this reason and to bring consistency to Next.js Middleware, this behavior will be deprecated soon in favor of always using absolute URLs. | ||
|
||
#### Possible Ways to Fix It | ||
|
||
To fix this warning you must always pass absolute URL for redirecting and rewriting. There are several ways to get the absolute URL but the recommended way is to clone `NextURL` and mutate it: | ||
|
||
```typescript | ||
import type { NextRequest } from 'next/server' | ||
import { NextResponse } from 'next/server' | ||
|
||
export function middleware(request: NextRequest) { | ||
const url = request.nextUrl.clone() | ||
url.pathname = '/dest' | ||
return NextResponse.rewrite(url) | ||
} | ||
``` | ||
|
||
Another way to fix this error could be to use the original URL as the base but this will not consider configuration like `basePath` or `locale`: | ||
|
||
```typescript | ||
import type { NextRequest } from 'next/server' | ||
import { NextResponse } from 'next/server' | ||
|
||
export function middleware(request: NextRequest) { | ||
return NextResponse.rewrite(new URL('/dest', request.url)) | ||
} | ||
``` | ||
|
||
You can also pass directly a string containing a valid absolute URL. | ||
|
||
### Useful Links | ||
|
||
- [URL Documentation](https://developer.mozilla.org/en-US/docs/Web/API/URL) | ||
- [Response Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Response) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
test/integration/middleware/core/pages/urls/_middleware.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { NextResponse, NextRequest } from 'next/server' | ||
|
||
export function middleware(request) { | ||
try { | ||
if (request.nextUrl.pathname === '/urls/relative-url') { | ||
return NextResponse.json({ message: String(new URL('/relative')) }) | ||
} | ||
|
||
if (request.nextUrl.pathname === '/urls/relative-request') { | ||
return fetch(new Request('/urls/urls-b')) | ||
} | ||
|
||
if (request.nextUrl.pathname === '/urls/relative-redirect') { | ||
return Response.redirect('/urls/urls-b') | ||
} | ||
|
||
if (request.nextUrl.pathname === '/urls/relative-next-redirect') { | ||
return NextResponse.redirect('/urls/urls-b') | ||
} | ||
|
||
if (request.nextUrl.pathname === '/urls/relative-next-rewrite') { | ||
return NextResponse.rewrite('/urls/urls-b') | ||
} | ||
|
||
if (request.nextUrl.pathname === '/urls/relative-next-request') { | ||
return fetch(new NextRequest('/urls/urls-b')) | ||
} | ||
} catch (error) { | ||
return NextResponse.json({ | ||
error: { | ||
message: error.message, | ||
}, | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export default function URLsA() { | ||
return <p className="title">URLs A</p> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export default function URLsB() { | ||
return <p className="title">URLs B</p> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
import { NextResponse } from 'next/server' | ||
|
||
export function middleware() { | ||
return NextResponse.rewrite('/about/a') | ||
export function middleware(request) { | ||
return NextResponse.rewrite(new URL('/about/a', request.url)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters