Skip to content
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

Add init to some NextResponse methods #38071

Merged
merged 3 commits into from
Jun 27, 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
25 changes: 15 additions & 10 deletions packages/next/server/web/spec-extension/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,34 @@ export class NextResponse extends 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)) {
throw new RangeError(
'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, {
headers: { Location: validateURL(url) },
...initObj,
headers,
status,
})
}

static rewrite(destination: string | NextURL | URL) {
return new NextResponse(null, {
headers: { 'x-middleware-rewrite': validateURL(destination) },
})
static rewrite(destination: string | NextURL | URL, init?: ResponseInit) {
const headers = new Headers(init?.headers)
headers.set('x-middleware-rewrite', validateURL(destination))
return new NextResponse(null, { ...init, headers })
}

static next() {
return new NextResponse(null, {
headers: { 'x-middleware-next': '1' },
})
static next(init?: ResponseInit) {
const headers = new Headers(init?.headers)
headers.set('x-middleware-next', '1')
return new NextResponse(null, { ...init, headers })
}
}

Expand Down
37 changes: 23 additions & 14 deletions test/e2e/middleware-general/app/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export async function middleware(request) {
const url = request.nextUrl

if (request.headers.get('x-prerender-revalidate')) {
const res = NextResponse.next()
res.headers.set('x-middleware', 'hi')
return res
return NextResponse.next({
headers: { 'x-middleware': 'hi' },
})
}

// this is needed for tests to get the BUILD_ID
Expand Down Expand Up @@ -187,6 +187,15 @@ export async function middleware(request) {
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')) {
try {
if (request.nextUrl.pathname === '/url/relative-url') {
Expand Down Expand Up @@ -229,18 +238,18 @@ export async function middleware(request) {
throw new Error('test error')
}

const response = NextResponse.next()
const original = new URL(request.url)
response.headers.set('req-url-path', `${original.pathname}${original.search}`)
response.headers.set('req-url-basepath', request.nextUrl.basePath)
response.headers.set('req-url-pathname', request.nextUrl.pathname)
response.headers.set('req-url-query', request.nextUrl.searchParams.get('foo'))
response.headers.set('req-url-locale', request.nextUrl.locale)
response.headers.set(
'req-url-params',
url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}'
)
return response
return NextResponse.next({
headers: {
'req-url-path': `${original.pathname}${original.search}`,
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-query': request.nextUrl.searchParams.get('foo'),
'req-url-locale': request.nextUrl.locale,
'req-url-params':
url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}',
},
})
}

function serializeData(data) {
Expand Down
16 changes: 16 additions & 0 deletions test/e2e/middleware-general/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
const browser = await webdriver(next.url, '/to-ssg')
await browser.eval('window.beforeNav = 1')
Expand Down
10 changes: 6 additions & 4 deletions test/e2e/middleware-rewrites/app/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ export async function middleware(request) {

if (url.pathname === '/rewrite-me-to-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') {
Expand Down Expand Up @@ -90,9 +92,9 @@ export async function middleware(request) {
? '/about-bypass'
: '/about'

const response = NextResponse.rewrite(url)
response.headers.set('x-middleware-cache', 'no-cache')
return response
return NextResponse.rewrite(url, {
headers: { 'x-middleware-cache': 'no-cache' },
})
}

if (url.pathname.endsWith('/dynamic-replace')) {
Expand Down