Use AMP in Next.js to speed up mobile loading

What is Accelerated Mobile Pages (AMP)?

AMP stands for "Accelerated Mobile Web Pages". It is an open source Web Components framework, initiated by Google and several other technology companies. With AMP, you can create simple mobile websites that load almost instantly. AMP is characterised by the reduction of JavaScript and CSS elements, and the use of CDN - Content Delivery Network.

AMP uses a simplified form of HTML to accelerate and improve the functionality of mobile pages, limiting HTML/CSS and JavaScript. Certain tags that are compatible with standard web code won't work with AMP. To make Google Search load faster, most AMP pages are cached by Google.

Google claims that AMP pages served in search typically load in less than a second and use one-tenth the data of regular pages.

How to use AMP with Next.js?

Before we can add AMP components to our webpage, we need to configure our page as an AMP page. If amp is set to true, it means your page will be a pure AMP version, if amp is set to hybrid (a hybrid AMP version), the page will have both an AMP version and an HTML version.

AMP web version (amp: true)

To enable AMP web version, add const config = { amp: true } to your page competent page.tsx or page.jsx

export const config = { amp: true } function Page(props) { return <h3>My first AMP page!</h3> } export default Page

The AMP page version will not run any Next.js or React code on the client side. This version uses AMP Optimizer to automatically optimize performance, improving performance by up to 42%, and users can load pages quickly. As well as having user accessible (optimized) versions of pages and search engine indexable (unoptimized) versions of pages.

AMP hybrid version (amp: “hybrid”)

In the AMP hybrid version, your page will have both the AMP version and the HTML version (by adding ?amp=1 to the URL). To use the hybrid version, first we load the useAmp hook suite and add const config = { amp: 'hybrid' } to your page eg page.tsx or page.jsx:

import { useAmp } from 'next/amp' export const config = { amp: 'hybrid' }

After that we can use useAmp() hook, this help us check whether the page is in amp mode, if it is amp we can conditionally Render the corresponding component element:

import { useAmp } from 'next/amp' export const config = { amp: 'hybrid' } function Page(props) { const isAmp = useAmp() return ( <div> <h3>My first AMP page!</h3> {/* Conditionally render the corresponding component element */} {isAmp ? ( // If it is an AMP page <amp-img width="200" height="200" src="/my-image.jpg" alt="an amp image" layout="responsive" /> ) : ( // If it is a non-AMP page <img width="200" height="200" src="/my-image.jpg" alt="an normal image" /> )} </div> ) } export default Page