Unverified Commit 364b4fe7 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Make sure rewrites are handled in serverless mode correctly (#10697)

Co-authored-by: 's avatarJoe Haddad <timer150@gmail.com>
parent c0f42837
...@@ -93,6 +93,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -93,6 +93,7 @@ const nextServerlessLoader: loader.Loader = function() {
const handleRewrites = ` const handleRewrites = `
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
const {prepareDestination} = require('next/dist/next-server/server/router')
function handleRewrites(parsedUrl) { function handleRewrites(parsedUrl) {
for (const rewrite of rewrites) { for (const rewrite of rewrites) {
...@@ -100,19 +101,14 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -100,19 +101,14 @@ const nextServerlessLoader: loader.Loader = function() {
const params = matcher(parsedUrl.pathname) const params = matcher(parsedUrl.pathname)
if (params) { if (params) {
parsedUrl.query = { const { parsedDestination } = prepareDestination(
...parsedUrl.query, rewrite.destination,
...params params
}
const parsedDest = parse(rewrite.destination)
const destCompiler = pathToRegexp.compile(
\`\${parsedDest.pathname}\${parsedDest.hash || ''}\`
) )
const newUrl = destCompiler(params) Object.assign(parsedUrl.query, parsedDestination.query, params)
const parsedNewUrl = parse(newUrl) delete parsedDestination.query
parsedUrl.pathname = parsedNewUrl.pathname Object.assign(parsedUrl, parsedDestination)
parsedUrl.hash = parsedNewUrl.hash
if (parsedUrl.pathname === '${page}'){ if (parsedUrl.pathname === '${page}'){
break break
...@@ -170,7 +166,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -170,7 +166,7 @@ const nextServerlessLoader: loader.Loader = function() {
` `
: '' : ''
} }
const parsedUrl = parse(req.url, true) const parsedUrl = handleRewrites(parse(req.url, true))
const params = ${ const params = ${
pageIsDynamicRoute pageIsDynamicRoute
......
...@@ -73,7 +73,11 @@ module.exports = { ...@@ -73,7 +73,11 @@ module.exports = {
}, },
{ {
source: '/api-hello-param/:name', source: '/api-hello-param/:name',
destination: '/api/hello?name=:name', destination: '/api/hello?hello=:name',
},
{
source: '/api-dynamic-param/:name',
destination: '/api/dynamic/:name?hello=:name',
}, },
{ {
source: '/:path/post-321', source: '/:path/post-321',
......
export default async (req, res) => res.json({ query: req.query })
const path = require('path')
const http = require('http')
const server = http.createServer((req, res) => {
const pagePath = page => path.join('.next/serverless/pages/', page)
const render = page => {
require(`./${pagePath(page)}`).render(req, res)
}
const apiCall = page => {
require(`./${pagePath(page)}`).default(req, res)
}
switch (req.url) {
case '/blog/post-1': {
return render('/blog/[post]')
}
case '/query-rewrite/first/second': {
return render('/with-params')
}
case '/api-hello-param/first': {
return apiCall('/api/hello')
}
case '/api-dynamic-param/first': {
return apiCall('/api/dynamic/[slug]')
}
default: {
res.statusCode(404)
return res.end('404')
}
}
})
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log('ready on', port)
})
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ import {
getBrowserBodyText, getBrowserBodyText,
waitFor, waitFor,
normalizeRegEx, normalizeRegEx,
initNextServerScript,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
...@@ -308,7 +309,9 @@ const runTests = (isDev = false) => { ...@@ -308,7 +309,9 @@ const runTests = (isDev = false) => {
it('should handle api rewrite with param successfully', async () => { it('should handle api rewrite with param successfully', async () => {
const data = await renderViaHTTP(appPort, '/api-hello-param/hello') const data = await renderViaHTTP(appPort, '/api-hello-param/hello')
expect(JSON.parse(data)).toEqual({ query: { name: 'hello' } }) expect(JSON.parse(data)).toEqual({
query: { name: 'hello', hello: 'hello' },
})
}) })
it('should handle encoded value in the pathname correctly', async () => { it('should handle encoded value in the pathname correctly', async () => {
...@@ -593,10 +596,15 @@ const runTests = (isDev = false) => { ...@@ -593,10 +596,15 @@ const runTests = (isDev = false) => {
source: '/api-hello-regex/(.*)', source: '/api-hello-regex/(.*)',
}, },
{ {
destination: '/api/hello?name=:name', destination: '/api/hello?hello=:name',
regex: normalizeRegEx('^\\/api-hello-param(?:\\/([^\\/]+?))$'), regex: normalizeRegEx('^\\/api-hello-param(?:\\/([^\\/]+?))$'),
source: '/api-hello-param/:name', source: '/api-hello-param/:name',
}, },
{
destination: '/api/dynamic/:name?hello=:name',
regex: normalizeRegEx('^\\/api-dynamic-param(?:\\/([^\\/]+?))$'),
source: '/api-dynamic-param/:name',
},
{ {
destination: '/with-params', destination: '/with-params',
regex: normalizeRegEx('^(?:\\/([^\\/]+?))\\/post-321$'), regex: normalizeRegEx('^(?:\\/([^\\/]+?))\\/post-321$'),
...@@ -608,6 +616,10 @@ const runTests = (isDev = false) => { ...@@ -608,6 +616,10 @@ const runTests = (isDev = false) => {
page: '/another/[id]', page: '/another/[id]',
regex: normalizeRegEx('^\\/another\\/([^\\/]+?)(?:\\/)?$'), regex: normalizeRegEx('^\\/another\\/([^\\/]+?)(?:\\/)?$'),
}, },
{
page: '/api/dynamic/[slug]',
regex: normalizeRegEx('^\\/api\\/dynamic\\/([^\\/]+?)(?:\\/)?$'),
},
{ {
page: '/blog/[post]', page: '/blog/[post]',
regex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'), regex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'),
...@@ -723,10 +735,77 @@ describe('Custom routes', () => { ...@@ -723,10 +735,77 @@ describe('Custom routes', () => {
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(async () => { afterAll(async () => {
await killApp(app)
await fs.writeFile(nextConfigPath, nextConfigContent, 'utf8') await fs.writeFile(nextConfigPath, nextConfigContent, 'utf8')
await killApp(app)
}) })
runTests() runTests()
}) })
describe('raw serverless mode', () => {
beforeAll(async () => {
nextConfigContent = await fs.readFile(nextConfigPath, 'utf8')
await fs.writeFile(
nextConfigPath,
nextConfigContent.replace(/\/\/ target/, 'target'),
'utf8'
)
await nextBuild(appDir)
appPort = await findPort()
app = await initNextServerScript(join(appDir, 'server.js'), /ready on/, {
...process.env,
PORT: appPort,
})
})
afterAll(async () => {
await fs.writeFile(nextConfigPath, nextConfigContent, 'utf8')
await killApp(app)
})
it('should apply rewrites in lambda correctly for page route', async () => {
const html = await renderViaHTTP(appPort, '/query-rewrite/first/second')
const data = JSON.parse(
cheerio
.load(html)('p')
.text()
)
expect(data).toEqual({
first: 'first',
second: 'second',
section: 'first',
name: 'second',
})
})
it('should apply rewrites in lambda correctly for dynamic route', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
expect(html).toContain('post-2')
})
it('should apply rewrites in lambda correctly for API route', async () => {
const data = JSON.parse(
await renderViaHTTP(appPort, '/api-hello-param/first')
)
expect(data).toEqual({
query: {
name: 'first',
hello: 'first',
},
})
})
it('should apply rewrites in lambda correctly for dynamic API route', async () => {
const data = JSON.parse(
await renderViaHTTP(appPort, '/api-dynamic-param/first')
)
expect(data).toEqual({
query: {
slug: 'first',
name: 'first',
hello: 'first',
},
})
})
})
}) })
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