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 { ...@@ -162,29 +162,6 @@ export default class Server {
] ]
if (this.nextConfig.useFileSystemPublicRoutes) { 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. // It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/') // (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack. // Otherwise this will lead to a pretty simple DOS attack.
...@@ -196,7 +173,13 @@ export default class Server { ...@@ -196,7 +173,13 @@ export default class Server {
if (!pathname) { if (!pathname) {
throw new Error('pathname is undefined') throw new Error('pathname is undefined')
} }
// 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) await this.render(req, res, pathname, query, parsedUrl)
}
}, },
}) })
} }
......
...@@ -85,7 +85,6 @@ function renderDocument( ...@@ -85,7 +85,6 @@ function renderDocument(
props, props,
docProps, docProps,
pathname, pathname,
asPath,
query, query,
buildId, buildId,
assetPrefix, assetPrefix,
...@@ -103,7 +102,6 @@ function renderDocument( ...@@ -103,7 +102,6 @@ function renderDocument(
props: any props: any
docProps: any docProps: any
pathname: string pathname: string
asPath: string | undefined
query: ParsedUrlQuery query: ParsedUrlQuery
amphtml: boolean amphtml: boolean
dynamicImportsIds: string[] dynamicImportsIds: string[]
...@@ -130,7 +128,6 @@ function renderDocument( ...@@ -130,7 +128,6 @@ function renderDocument(
err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
}} }}
ampEnabled={ampEnabled} ampEnabled={ampEnabled}
asPath={encodeURI(asPath || '')}
amphtml={amphtml} amphtml={amphtml}
staticMarkup={staticMarkup} staticMarkup={staticMarkup}
devFiles={devFiles} devFiles={devFiles}
...@@ -249,7 +246,6 @@ export async function renderToHTML( ...@@ -249,7 +246,6 @@ export async function renderToHTML(
...renderOpts, ...renderOpts,
props, props,
docProps, docProps,
asPath,
pathname, pathname,
amphtml, amphtml,
query, query,
......
...@@ -111,7 +111,7 @@ export class Head extends Component { ...@@ -111,7 +111,7 @@ export class Head extends Component {
} }
render () { 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 { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId } = __NEXT_DATA__ const { page, buildId } = __NEXT_DATA__
...@@ -131,7 +131,7 @@ export class Head extends Component { ...@@ -131,7 +131,7 @@ export class Head extends Component {
{head} {head}
{amphtml && <> {amphtml && <>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"/> <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 */} {/* 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" /> <link rel="preload" as="script" href="https://cdn.ampproject.org/v0.js" />
{/* Add custom styles before AMP styles to prevent accidental overrides */} {/* Add custom styles before AMP styles to prevent accidental overrides */}
...@@ -141,7 +141,7 @@ export class Head extends Component { ...@@ -141,7 +141,7 @@ export class Head extends Component {
<script async src="https://cdn.ampproject.org/v0.js"></script> <script async src="https://cdn.ampproject.org/v0.js"></script>
</>} </>}
{!amphtml && <> {!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} />} {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} /> <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()} {this.getPreloadDynamicChunks()}
......
...@@ -24,11 +24,12 @@ async function validateAMP (html) { ...@@ -24,11 +24,12 @@ async function validateAMP (html) {
if (result.status !== 'PASS') { if (result.status !== 'PASS') {
for (let ii = 0; ii < result.errors.length; ii++) { for (let ii = 0; ii < result.errors.length; ii++) {
const error = result.errors[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) { if (error.specUrl !== null) {
msg += ' (see ' + error.specUrl + ')' 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') expect(result.status).toBe('PASS')
...@@ -57,24 +58,32 @@ describe('AMP Usage', () => { ...@@ -57,24 +58,32 @@ describe('AMP Usage', () => {
describe('With basic AMP usage', () => { describe('With basic AMP usage', () => {
it('should render the page as valid AMP', async () => { 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) await validateAMP(html)
expect(html).toMatch(/Hello World/) expect(html).toMatch(/Hello World/)
}) })
it('should add link preload for amp script', async () => { 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) await validateAMP(html)
const $ = cheerio.load(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 () => { 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) await validateAMP(html)
const $ = cheerio.load(html) const $ = cheerio.load(html)
const order = [] const order = []
$('style').toArray().forEach((i) => { $('style')
.toArray()
.forEach(i => {
if ($(i).attr('amp-custom') === '') { if ($(i).attr('amp-custom') === '') {
order.push('amp-custom') order.push('amp-custom')
} }
...@@ -83,7 +92,11 @@ describe('AMP Usage', () => { ...@@ -83,7 +92,11 @@ describe('AMP Usage', () => {
} }
}) })
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', () => { ...@@ -94,7 +107,7 @@ describe('AMP Usage', () => {
}) })
it('should render the AMP page that uses the AMP hook', async () => { 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) await validateAMP(html)
expect(html).toMatch(/Hello AMP/) expect(html).toMatch(/Hello AMP/)
}) })
...@@ -104,14 +117,22 @@ describe('AMP Usage', () => { ...@@ -104,14 +117,22 @@ describe('AMP Usage', () => {
it('should render link rel amphtml', async () => { it('should render link rel amphtml', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook') const html = await renderViaHTTP(appPort, '/use-amp-hook')
const $ = cheerio.load(html) 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 () => { 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) const $ = cheerio.load(html)
await validateAMP(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