Unverified Commit 6dfcacb7 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Use a query parameter for AMP pages instead of new route (#6336)

Per consensus in a mixed-application scenario, we'll use the `amp` query parameter convention.
parent f9fedaeb
......@@ -162,29 +162,6 @@ export default class Server {
]
if (this.nextConfig.useFileSystemPublicRoutes) {
if (this.nextConfig.experimental.amp) {
// It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/zeit/next.js/issues/2617
routes.push({
match: route('/:path*/amp'),
fn: async (req, res, params, parsedUrl) => {
let pathname
if (!params.path) {
pathname = '/'
} else {
pathname = '/' + params.path.join('/')
}
const { query } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
await this.renderToAMP(req, res, pathname, query, parsedUrl)
},
})
}
// It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
......@@ -196,7 +173,13 @@ export default class Server {
if (!pathname) {
throw new Error('pathname is undefined')
}
await this.render(req, res, pathname, query, parsedUrl)
// Currently, we will render amp even if the user passes `?amp=0`.
if (this.nextConfig.experimental.amp && query.amp) {
await this.renderToAMP(req, res, pathname, query, parsedUrl)
} else {
await this.render(req, res, pathname, query, parsedUrl)
}
},
})
}
......
......@@ -85,7 +85,6 @@ function renderDocument(
props,
docProps,
pathname,
asPath,
query,
buildId,
assetPrefix,
......@@ -103,7 +102,6 @@ function renderDocument(
props: any
docProps: any
pathname: string
asPath: string | undefined
query: ParsedUrlQuery
amphtml: boolean
dynamicImportsIds: string[]
......@@ -130,7 +128,6 @@ function renderDocument(
err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
}}
ampEnabled={ampEnabled}
asPath={encodeURI(asPath || '')}
amphtml={amphtml}
staticMarkup={staticMarkup}
devFiles={devFiles}
......@@ -249,7 +246,6 @@ export async function renderToHTML(
...renderOpts,
props,
docProps,
asPath,
pathname,
amphtml,
query,
......
......@@ -111,7 +111,7 @@ export class Head extends Component {
}
render () {
const { asPath, ampEnabled, head, styles, amphtml, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
const { ampEnabled, head, styles, amphtml, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId } = __NEXT_DATA__
......@@ -131,7 +131,7 @@ export class Head extends Component {
{head}
{amphtml && <>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"/>
<link rel="canonical" href={asPath === '/amp' ? '/' : asPath.replace(/\/amp$/, '')} />
<link rel="canonical" href={page} />
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link rel="preload" as="script" href="https://cdn.ampproject.org/v0.js" />
{/* Add custom styles before AMP styles to prevent accidental overrides */}
......@@ -141,7 +141,7 @@ export class Head extends Component {
<script async src="https://cdn.ampproject.org/v0.js"></script>
</>}
{!amphtml && <>
{ampEnabled && <link rel="amphtml" href={asPath === '/' ? '/amp' : (asPath.replace(/\/$/, '') + '/amp')} />}
{ampEnabled && <link rel="amphtml" href={`${page}?amp=1`} />}
{page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${getPagePathname(page)}${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
<link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />
{this.getPreloadDynamicChunks()}
......
......@@ -24,11 +24,12 @@ async function validateAMP (html) {
if (result.status !== 'PASS') {
for (let ii = 0; ii < result.errors.length; ii++) {
const error = result.errors[ii]
let msg = 'line ' + error.line + ', col ' + error.col + ': ' + error.message
let msg =
'line ' + error.line + ', col ' + error.col + ': ' + error.message
if (error.specUrl !== null) {
msg += ' (see ' + error.specUrl + ')'
}
((error.severity === 'ERROR') ? console.error : console.warn)(msg)
;(error.severity === 'ERROR' ? console.error : console.warn)(msg)
}
}
expect(result.status).toBe('PASS')
......@@ -57,33 +58,45 @@ describe('AMP Usage', () => {
describe('With basic AMP usage', () => {
it('should render the page as valid AMP', async () => {
const html = await renderViaHTTP(appPort, '/amp')
const html = await renderViaHTTP(appPort, '/?amp=1')
await validateAMP(html)
expect(html).toMatch(/Hello World/)
})
it('should add link preload for amp script', async () => {
const html = await renderViaHTTP(appPort, '/amp')
const html = await renderViaHTTP(appPort, '/?amp=1')
await validateAMP(html)
const $ = cheerio.load(html)
expect($($('link[rel=preload]').toArray().find(i => $(i).attr('href') === 'https://cdn.ampproject.org/v0.js')).attr('href')).toBe('https://cdn.ampproject.org/v0.js')
expect(
$(
$('link[rel=preload]')
.toArray()
.find(i => $(i).attr('href') === 'https://cdn.ampproject.org/v0.js')
).attr('href')
).toBe('https://cdn.ampproject.org/v0.js')
})
it('should add custom styles before amp boilerplate styles', async () => {
const html = await renderViaHTTP(appPort, '/amp')
const html = await renderViaHTTP(appPort, '/?amp=1')
await validateAMP(html)
const $ = cheerio.load(html)
const order = []
$('style').toArray().forEach((i) => {
if ($(i).attr('amp-custom') === '') {
order.push('amp-custom')
}
if ($(i).attr('amp-boilerplate') === '') {
order.push('amp-boilerplate')
}
})
$('style')
.toArray()
.forEach(i => {
if ($(i).attr('amp-custom') === '') {
order.push('amp-custom')
}
if ($(i).attr('amp-boilerplate') === '') {
order.push('amp-boilerplate')
}
})
expect(order).toEqual(['amp-custom', 'amp-boilerplate', 'amp-boilerplate'])
expect(order).toEqual([
'amp-custom',
'amp-boilerplate',
'amp-boilerplate'
])
})
})
......@@ -94,7 +107,7 @@ describe('AMP Usage', () => {
})
it('should render the AMP page that uses the AMP hook', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook/amp')
const html = await renderViaHTTP(appPort, '/use-amp-hook?amp=1')
await validateAMP(html)
expect(html).toMatch(/Hello AMP/)
})
......@@ -104,14 +117,22 @@ describe('AMP Usage', () => {
it('should render link rel amphtml', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook')
const $ = cheerio.load(html)
expect($('link[rel=amphtml]').first().attr('href')).toBe('/use-amp-hook/amp')
expect(
$('link[rel=amphtml]')
.first()
.attr('href')
).toBe('/use-amp-hook?amp=1')
})
it('should render the AMP page that uses the AMP hook', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook/amp')
const html = await renderViaHTTP(appPort, '/use-amp-hook?amp=1')
const $ = cheerio.load(html)
await validateAMP(html)
expect($('link[rel=canonical]').first().attr('href')).toBe('/use-amp-hook')
expect(
$('link[rel=canonical]')
.first()
.attr('href')
).toBe('/use-amp-hook')
})
})
})
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