SimpleNext.js
How to create AMP pages with Next.js
What is AMP?
AMP (Accelerated Mobile Pages) is an HTML open source framework backed by google . AMP pages are optimized for speed especially for Mobile web browsing.
Why use AMP?
AMP offers a better User experience on mobile by loading pages faster, and google tends to rank AMP pages higher than equivalent ordinary HTML pages
AMP and Next.js
You can turn any Next.js page to an AMP page by a simple config.
To enable AMP, add the following config to your page:
export const config = { amp: true }
The amp config accepts the following values:
- true - The page will be AMP-only
- 'hybrid' - The page will have two versions, one with AMP and another one with HTML
AMP Only page
You can create AMP only pages by using the true value to the amp config :
export const config = { amp: true }
function Hello(props) {
return <h3> AMP Hello world</h3>
}
export default Hello
Hybrid AMP
import { useAmp } from 'next/amp'
export const config = { amp: 'hybrid' }
function About(props) {
const isAmp = useAmp()
return (
<div>
<h3>My AMP About Page!</h3>
{isAmp ? (
<amp-img
width="300"
height="300"
src="/my-img.jpg"
alt="a cool image"
layout="responsive"
/>
) : (
<img width="300" height="300"
src="/my-img.jpg" alt="a cool image" />
)}
</div>
)
}
export default About
The page above is a hybrid AMP page, which means:
- The page is rendered as traditional HTML (default) and AMP HTML (by adding ?amp=1 to the URL)
- The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines The page uses useAmp to differentiate between modes, it's a React Hook that returns true if the page is using AMP, and false otherwise.
AMP with Next.js caveats
You need to use custom components for images, ads, fonts , js scripts, … It can lead to rewrite a lot of the code CSS in external files ( or component librairies ) would not work! you need to use CSS-In-JS or AMP CSS frameworks.