Skip to content

Commit

Permalink
fix: updated redirect data urls (#1928)
Browse files Browse the repository at this point in the history
* fix: updated redirect data urls

* fix: typescript errors and accidental deletion

* fix: console logging test

* fix: getting the redirect header and normalizing url outisde of orig if statement

* fix: added ref link

* fix: removing console.log

* fix: commenting/reverting changes for testing

* fix: undo "commenting/reverting changes.."

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
taty2010 and kodiakhq[bot] committed Mar 14, 2023
1 parent 89904cb commit 1edaacb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
22 changes: 22 additions & 0 deletions packages/runtime/src/templates/edge-shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,22 @@ export interface FetchEventResult {

type NextDataTransform = <T>(data: T) => T

function normalizeDataUrl(redirect: string) {
// If the redirect is a data URL, we need to normalize it.
// next.js code reference: https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/router/utils/get-next-pathname-info.ts#L46
if (redirect.startsWith('/_next/data/') && redirect.includes('.json')) {
const paths = redirect
.replace(/^\/_next\/data\//, '')
.replace(/\.json/, '')
.split('/')

const buildId = paths[0]
redirect = paths[1] !== 'index' ? `/${paths.slice(1).join('/')}` : '/'
}

return redirect
}

/**
* This is how Next handles rewritten URLs.
*/
Expand Down Expand Up @@ -249,6 +265,12 @@ export const buildResponse = async ({
res.headers.set('x-nextjs-redirect', relativizeURL(redirect, request.url))
}

const nextRedirect = res.headers.get('x-nextjs-redirect')

if (nextRedirect && isDataReq) {
res.headers.set('x-nextjs-redirect', normalizeDataUrl(nextRedirect))
}

if (res.headers.get('x-middleware-next') === '1') {
return addMiddlewareHeaders(context.next(), res)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,13 @@ describe('Middleware Redirect', () => {
expect(res.headers.get('location')?.endsWith('/default/about')).toEqual(false)
})

usuallySkip(`should redirect to data urls with data requests and internal redirects`, async () => {
it(`should redirect to data urls with data requests and internal redirects`, async () => {
const res = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/es/old-home.json`,
{ override: 'internal' },
{ redirect: 'manual', headers: { 'x-nextjs-data': '1' } },
)

expect(res.headers.get('x-nextjs-redirect')?.endsWith(`/es/new-home?override=internal`)).toEqual(true)
expect(res.headers.get('location')).toEqual(null)
})
Expand Down

0 comments on commit 1edaacb

Please sign in to comment.