Unverified Commit ca621ced authored by Javi Velasco's avatar Javi Velasco Committed by GitHub

Add `init` to some `NextResponse` methods (#38071)

* Add `init` to some `NextResponse` methods

* Add NextResponse.redirect test and fix headers
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent d7e83704
...@@ -37,29 +37,34 @@ export class NextResponse extends Response { ...@@ -37,29 +37,34 @@ export class NextResponse extends Response {
return new NextResponse(response.body, response) return new NextResponse(response.body, response)
} }
static redirect(url: string | NextURL | URL, status = 307) { static redirect(url: string | NextURL | URL, init?: number | ResponseInit) {
const status = typeof init === 'number' ? init : init?.status ?? 307
if (!REDIRECTS.has(status)) { if (!REDIRECTS.has(status)) {
throw new RangeError( throw new RangeError(
'Failed to execute "redirect" on "response": Invalid status code' 'Failed to execute "redirect" on "response": Invalid status code'
) )
} }
const initObj = typeof init === 'object' ? init : {}
const headers = new Headers(initObj?.headers)
headers.set('Location', validateURL(url))
return new NextResponse(null, { return new NextResponse(null, {
headers: { Location: validateURL(url) }, ...initObj,
headers,
status, status,
}) })
} }
static rewrite(destination: string | NextURL | URL) { static rewrite(destination: string | NextURL | URL, init?: ResponseInit) {
return new NextResponse(null, { const headers = new Headers(init?.headers)
headers: { 'x-middleware-rewrite': validateURL(destination) }, headers.set('x-middleware-rewrite', validateURL(destination))
}) return new NextResponse(null, { ...init, headers })
} }
static next() { static next(init?: ResponseInit) {
return new NextResponse(null, { const headers = new Headers(init?.headers)
headers: { 'x-middleware-next': '1' }, headers.set('x-middleware-next', '1')
}) return new NextResponse(null, { ...init, headers })
} }
} }
......
...@@ -37,9 +37,9 @@ export async function middleware(request) { ...@@ -37,9 +37,9 @@ export async function middleware(request) {
const url = request.nextUrl const url = request.nextUrl
if (request.headers.get('x-prerender-revalidate')) { if (request.headers.get('x-prerender-revalidate')) {
const res = NextResponse.next() return NextResponse.next({
res.headers.set('x-middleware', 'hi') headers: { 'x-middleware': 'hi' },
return res })
} }
// this is needed for tests to get the BUILD_ID // this is needed for tests to get the BUILD_ID
...@@ -187,6 +187,15 @@ export async function middleware(request) { ...@@ -187,6 +187,15 @@ export async function middleware(request) {
return NextResponse.rewrite(new URL('/about/a', request.url)) return NextResponse.rewrite(new URL('/about/a', request.url))
} }
if (url.pathname === '/redirect-to-somewhere') {
url.pathname = '/somewhere'
return NextResponse.redirect(url, {
headers: {
'x-redirect-header': 'hi',
},
})
}
if (url.pathname.startsWith('/url')) { if (url.pathname.startsWith('/url')) {
try { try {
if (request.nextUrl.pathname === '/url/relative-url') { if (request.nextUrl.pathname === '/url/relative-url') {
...@@ -229,18 +238,18 @@ export async function middleware(request) { ...@@ -229,18 +238,18 @@ export async function middleware(request) {
throw new Error('test error') throw new Error('test error')
} }
const response = NextResponse.next()
const original = new URL(request.url) const original = new URL(request.url)
response.headers.set('req-url-path', `${original.pathname}${original.search}`) return NextResponse.next({
response.headers.set('req-url-basepath', request.nextUrl.basePath) headers: {
response.headers.set('req-url-pathname', request.nextUrl.pathname) 'req-url-path': `${original.pathname}${original.search}`,
response.headers.set('req-url-query', request.nextUrl.searchParams.get('foo')) 'req-url-basepath': request.nextUrl.basePath,
response.headers.set('req-url-locale', request.nextUrl.locale) 'req-url-pathname': request.nextUrl.pathname,
response.headers.set( 'req-url-query': request.nextUrl.searchParams.get('foo'),
'req-url-params', 'req-url-locale': request.nextUrl.locale,
url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}' 'req-url-params':
) url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}',
return response },
})
} }
function serializeData(data) { function serializeData(data) {
......
...@@ -149,6 +149,22 @@ describe('Middleware Runtime', () => { ...@@ -149,6 +149,22 @@ describe('Middleware Runtime', () => {
}) })
} }
it('should have init header for NextResponse.redirect', async () => {
const res = await fetchViaHTTP(
next.url,
'/redirect-to-somewhere',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
expect(new URL(res.headers.get('location'), 'http://n').pathname).toBe(
'/somewhere'
)
expect(res.headers.get('x-redirect-header')).toBe('hi')
})
it('should have correct query values for rewrite to ssg page', async () => { it('should have correct query values for rewrite to ssg page', async () => {
const browser = await webdriver(next.url, '/to-ssg') const browser = await webdriver(next.url, '/to-ssg')
await browser.eval('window.beforeNav = 1') await browser.eval('window.beforeNav = 1')
......
...@@ -54,7 +54,9 @@ export async function middleware(request) { ...@@ -54,7 +54,9 @@ export async function middleware(request) {
if (url.pathname === '/rewrite-me-to-about') { if (url.pathname === '/rewrite-me-to-about') {
url.pathname = '/about' url.pathname = '/about'
return NextResponse.rewrite(url) return NextResponse.rewrite(url, {
headers: { 'x-rewrite-target': String(url) },
})
} }
if (url.pathname === '/rewrite-me-with-a-colon') { if (url.pathname === '/rewrite-me-with-a-colon') {
...@@ -90,9 +92,9 @@ export async function middleware(request) { ...@@ -90,9 +92,9 @@ export async function middleware(request) {
? '/about-bypass' ? '/about-bypass'
: '/about' : '/about'
const response = NextResponse.rewrite(url) return NextResponse.rewrite(url, {
response.headers.set('x-middleware-cache', 'no-cache') headers: { 'x-middleware-cache': 'no-cache' },
return response })
} }
if (url.pathname.endsWith('/dynamic-replace')) { if (url.pathname.endsWith('/dynamic-replace')) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment