Next.js next/amp
Last Updated :
26 Apr, 2023
Next.js is a popular React-based web framework that allows developers to build high-performance, server-rendered React applications easily. It provides many features that ease the development of React applications, including server-side rendering, static site generation, and automatic code splitting.
Next.js also provides support for creating Accelerated Mobile Pages (AMP) with its next/amp module. AMP is an open-source framework created by Google that allows developers to create web pages that load quickly on mobile devices by optimizing their performance.
The Next.js next/amp module provides developers with the tools and components necessary to create AMP-compliant web pages. This includes a set of optimized React components that can be used to create AMP pages, as well as a suite of utilities that help ensure compliance with the AMP specification.
To use the next/amp module use the following steps-
Step 1: Install NodeJS. Follow one of the links to install according to your system, Windows and Linux.
Step 2: Here’s the syntax to use next/amp in your Next.js application:
import { useAmp } from 'next/amp';
Step 3: Install the required dependency for Next.js project.
npx create-next-app my-app
cd my-app
npm install next-amp
Note: The above command is automatically set up folders and files.
Step 5: In this example, we’re using useAmp hook provided by the next/amp module to determine whether the page is being rendered as an AMP page or not.
Example: We’re also setting the amp property in the config object to ‘hybrid‘, which tells Next.js that this page should be rendered as a hybrid AMP page.
Filename: index.js
Javascript
import { useAmp } from 'next/amp' ;
export const config = {
amp: 'hybrid'
}
const AMPExample = () => {
const isAmp = useAmp();
return (
<div>
<h1>
{isAmp ? 'This is an AMP page!' :
'This is a regular page!' }
</h1>
<p>
Hi this is an AMP page
</p>
</div>
);
};
export default AMPExample;
|
Step 6: Run the Code: To run the Application open the terminal( VS code terminal press (Ctrl+shift+`)) and type the following command
npm run dev
After Successful Compilation open the browser and type the following URL.
http://localhost:3000/
Output:
NextJs next/amp
Reference: https://nextjs.org/docs/api-reference/next/amp
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...