Next.js is an open-source, lightweight React.js framework that gives you building blocks to create web applications. Next.js was first released as an open-source project on GitHub on October 25, 2016. It was created by Zeit. By this framework, mean Next.js handles the tooling and configuration needed for React, and provides additional structure, features, and optimizations for your web application. NextJS's features :webpack and transformed using a compiler like Babel.pre-render some pages for performance and SEO statically. You might also want to use server-side rendering or client-side rendering.Next.js fulfills the above all requirements.Next.js :Next.js provides automatic code-splitting, filesystem-based routing, hot code reloading, and universal rendering; that's why the world's leading companies prefer it.Next.js is fully extensible and has complete control over Babel and Webpack. It provides a customizable server, routing, and next plugins.Next.js is optimized for smaller build sizes, faster dev compilation, and many other improvements, making it a popular choice.Next.js can Deploy Anywhere : Next.js is an open-source, lightweight React.js framework that facilitates developers to build static and server-side rendering web applications.CMS, auth, payments, etc) and how you connect to them.Node.js 12.22.0 or laterNext.js app using create-next-app, which sets up everything automatically for you. To create a project, run:npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app
--typescript flag :npx create-next-app@latest --typescript
# or
yarn create next-app --typescript
# or
pnpm create next-app --typescript
npm run dev or yarn dev or pnpm dev to start the development server on http://localhost:3000http://localhost:3000 to view your applicationpages/index.js and see the updated result in your browsernext, react and react-dom in your project:npm install next react react-dom
# or
yarn add next react react-dom
# or
pnpm add next react react-dom
package.json and add the following scripts :"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
dev - Runs next dev to start Next.js in development modebuild - Runs next build to build the application for production usagestart - Runs next start to start a Next.js production serverlint - Runs next lint to set up Next.js' built-in ESLint configurationpages and public at the root of your application:pages - Associated with a route based on their file name. For example pages/about.js is mapped to /aboutpublic - Stores static assets such as images, fonts, etc. Files inside public directory can then be referenced by your code starting from the base URL (/).Next.js is built around the concept of pages. A page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. You can even add dynamic route parameters with the filename.index.js file to get started. This is the page that is rendered when the user visits the root of your applicationpages/index.js with the following contents :function HomePage() {
return <div>Welcome to Next.js!</div>
}
export default HomePage
npm run dev or yarn dev or pnpm dev to start the development server on http://localhost:3000http://localhost:3000 to view your applicationpages/index.js and see the updated result in your browserNext.js is a popular framework of React.js that is most popularly used for building the following types of apps and websites :Next.js, but Next.js itself recommends getInitialProps, an async function to retrieve data from anywhere. When we use getInitialProps to retrieve data, it receives a context object which has the following properties :app.disable('etag') syntax to disable the etag generation in Next.js. But, this may not work for all static contents. So, we should use the following syntax to disable the etag for all static contents.app.use(express.static(path.join(__dirname, 'public'), {
etag: false
}));
build-id in Next.js, we must configure a static ID between our builds. So, we have to provide the "generateBuildId" function with the following configuration.// next.config.js
module.exports = {
generateBuildId: async () => {
// For example get the latest git commit hash here
return 'my-build-id';
}
};
create-next-app allows you to create a new Next.js app within seconds. It is officially maintained by the creators of Next.js, and includes a number of benefits :create-next-app@latest (with no arguments) launches an interactive experience that guides you through setting up a project.Next.js examples collection (e.g. npx create-next-app --example api-routes).Next.js monorepo and tested using the same integration test suite as Next.js itself, ensuring it works as expected with every release.Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with Server-side Rendering or Static Generation, and updating or creating content at runtime with Incremental Static Regeneration. Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when the content of your pages needs to update frequently. Unlike the server-side rendering APIs, you can use client-side data fetching at the component level.client-side data fetching can affect the performance of your application and the load speed of your pages. This is because the data fetching is done at the time of the component or pages mount, and the data is not cached.Next.js has created a React hook library for data fetching called SWR (stale-while-revalidate). It is highly recommended if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more.import useSWR from 'swr'
const fetcher = (...args) => fetch(...args).then((res) => res.json())
function Profile() {
const { data, error } = useSWR('/api/profile-data', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}
getServerSideProps (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
When does getServerSideProps run : getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps, then:
When you request this page directly, getServerSideProps runs at request time, and this page will be pre-rendered with the returned props
When you request this page on client-side page transitions through next/link or next/router, Next.js sends an API request to the server, which runs getServerSideProps
getServerSideProps returns JSON which will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have getServerSideProps defined.
You can use the next-code-elimination tool to verify what Next.js eliminates from the client-side bundle.
getServerSideProps can only be exported from a page. You can’t export it from non-page files.
Note that you must export getServerSideProps as a standalone function — it will not work if you add getServerSideProps as a property of the page component.
getStaticProps (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
getStaticProps if :getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performanceNext.js Image component, next/image, is an extension of the HTML <img> element, evolved for the modern web. It includes a variety of built-in performance optimizations to help you achieve good Core Web Vitals. These scores are an important measurement of user experience on your website, and are factored into Google's search rankings..env.local to load environment variablesNEXT_PUBLIC_.env.local file is needed. However, sometimes you might want to add some defaults for the development (next dev) or production (next start) environment..env (all environments), .env.development (development environment), and .env.production (production environment)..env.local always overrides the defaults set.pages directory, it's automatically available as a route.pages directory can be used to define most common patterns.index to the root of the directory.pages/index.js → /pages/blog/index.js → /blogpages/blog/first-post.js → /blog/first-postpages/dashboard/settings/username.js → /dashboard/settings/usernamepages/blog/[slug].js → /blog/:slug (/blog/hello-world)pages/[username]/settings.js → /:username/settings (/foo/settings)pages/post/[...all].js → /post/* (/post/2020/id/title)Next.js can be deployed to any hosting provider that supports Docker containers. You can use this approach when deploying to container orchestrators such as Kubernetes or HashiCorp Nomad, or when running inside a single node in any cloud provider.Install Docker on your machinewith-docker exampledocker build -t nextjs-docker .docker run -p 3000:3000 nextjs-dockerwith-docker-multi-env example../pages/index.js with the following contents:function HomePage() {
return <div>Welcome to Next.js!</div>
}
server on http://localhost:3000. Now we can visit the localhost: http://localhost:3000 to view our application.a _error.js in the pages folder. See the following example :import React from "react";
class Error extends React.Component {
static getInitialProps({ res, err }) {
const statusCode = res ? res.statusCode : err ? err.statusCode : null;
return { statusCode };
}
render() {
return (
{this.props.statusCode
? `An error ${this.props.statusCode} has occurred on the server`
: "An error occurred on client-side"}
);
}
}
export default Error;
Gatsby and Next.js the same thing mostly because they almost perform the same function. However, the two frameworks are different and feature a couple of similarities at first glance. They include:Next.js and Gatsby develop SPA out of the box| Next.Js | React |
|---|---|
|
|
|
|
|
|
|
|
|
|
AMP in Next.js.AMP-First Pages are served to the primary traffic of the website as well as traffic generated from the search engine. Use the following syntax to implement AMP-first pages.// pages/index.js
import { withAmp } from 'next/amp'
function HomePage() {
return <p> Welcome to AMP + Next.js.</p>
}
export default withAmp(HomePage)
Hybrid AMP pages allow the users to have coexisted AMP version of a traditional page so that the search engines can display the AMP version or the page in different mobile search results.Hybrid AMP to pages :// pages/index.js
import { withAmp } from 'next/amp'
function HomePage() {
return <p> Welcome to AMP + Next.js.</p>
}
export default withAmp(HomePage)
next.config.js :module.exports = {
experimental: {
urlImports: ['https://example.com/modules/'],
},
}
import { a, b, c } from 'https://example.com/modules/some/module.js'
static optimization can be very beneficial and knowing immediately in development if the page qualifies can be useful.next.config.js and disable the autoPrerender config in devIndicators:module.exports = {
devIndicators: {
autoPrerender: false,
},
}
Next.js is compiling the application, a compilation indicator appears in the bottom right corner of the page.next.config.js and set the buildActivityPosition in the devIndicators object to bottom-right (default), bottom-left, top-right or top-left:module.exports = {
devIndicators: {
buildActivityPosition: 'bottom-right',
},
}
next.config.js and disable the buildActivity config in devIndicators object :module.exports = {
devIndicators: {
buildActivity: false,
},
}