Beginners Guide To Next.js
What is Next.js
Next.js is an open-source development framework built on top of Node.js which enables React-based web applications to perform server-side rendering and generate static websites. It has all the tools that you need to make the web faster. It enables React-based websites to be SEO-ready with some best practices
Prerequisites
This blog assumes some familiarity with JavaScript and React. If you’ve never written React code, you should go through the official React tutorial first
Features of Next.js
- An intuitive page-based routing system (with support for dynamic routes)
- Pre-rendering, both static generation (SSG) and server-side rendering (SSR) are supported on a per-page basis
- Automatic code splitting for faster page loads
- Client-side routing with optimised prefetching
- Built-in CSS and Sass support, and support for any CSS-in-JS library
- Development environment with Fast Refresh support
- API routes to build API endpoints with Server less Functions
- Image Optimisation
Creating a next-app
Make sure Node.js 10.13 or later is installed. Install Node.js from the following link.
Download | Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
Use the command below to check version of Node.js installed.
node --version
You can use any IDE of your choice. I would suggest Visual Studio Code
- Create a folder on your machine
- Open that folder in visual studio code
- Open the terminal
- Run the following command to create a next app
npx create-next-app <appname>
5. Navigate to the project folder
Run the following command to run the development server on port 3000
npm run dev
Congratulations! Your next-app is running on http://localhost:3000
Understanding Folder Structure
In our root folder ‘next-learn’ we have many sub-folders and files. Let us see them one by one
package.json — contains the dependencies and the scripts required for the project
.next — generated when we run build or dev scripts. Our application is served from this folder
node_modules — all the dependencies are installed
styles — contains some styles for our application. Contains global as well as component level styles. Just for better organisation
Public — files in this folder are directly accessible by anyone. Next.js serves files in this directory as it is.
Pages — This folder is the heart of our application. It contains the source code of the application. Routing is also based on this folder.
gitignore — version control with git
Readme .md— contains few instructions related to running , building and deploying the application
next.config.js — The next js configuration file
Eslintrc — configuration file for eslint
Development Server vs Production Server
To run our Next.js application in development mode with hot reloading
npm run dev
To compile application and prepare it for production deployment
npm run build
Start the compiled application in production mode
npm run start
How does Next.js code actually work
When we run the script ‘npm run dev’ the execution is transferred to _app.js which contains a MyApp component. This component automatically receives a component and page props which are returned as a part of jsx. When we navigate to the component prop will refer to the component defined in index.js
To learn more about this visit — https://nextjs.org/learn/foundations/how-nextjs-works
File-based Routing
When a file is added to the pages folder, it automatically becomes available as a route. By mixing and matching files names with a nested folder structure, it is possible to pretty much define the most common routing patterns
Link Component
It enables client side route transitions without page reload, just like react. Link accepts href as props for routing.
When I click on click here, it will navigate to /test without page reload.
useRouter hook — This hook is also used for routing. It contains many methods, you can see them here
Head Component
This component is like html <head> tag and can contain everything which an html head tag can contain.
Pre-rendering and Data fetching
Data fetching in 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.
- Server-side Rendering (SSR)
- Static-site Generation (SSG)
- Incremental Static Regeneration (ISR)
- Client-side Rendering (CSR)
Server-side Rendering — Exporting a function called ‘getServerSideProps’ from a page will pre-render that page on each request. ‘getServerSideProps’ will run on the server-side and the server will send rendered files to the client.
This is an inefficient approach as server will have to process data or send a request to the API at every request, this reduces performance and speed of the website.
The code above illustrates how to use the getServerSideProps method for server side rendering. This method will run on each request and will fetch data from the external JSONPlaceholder API.
Whenever this page is requested, data from the API will be pre-rendered at the server side and the pre-rendered document will be sent to the client
Static-site Generation — A method of pre-rendering where HTML pages are generated at build time. Exporting a function called ‘getStaticProps’ from a page will pre-render that page at build time using the props returned by ‘getStaticProps’. getStaticProps will always run on server side at build time. Page is built once, cached by a CDN and then served to the client almost instantly
In case APIs are called in getStaticProps and the API data changes, the server would serve the page with stale data as the page was generated at build time.
When the application is running in development mode, getStaticProps is called on every request. So we can see the time being updated when we refresh but when the application is running in production mode, getStaticProps will be called at build time and page generated at build time will be sent to the client
As you can see, the time is not being updated after refreshing as cached page is getting served. This is a big problem in applications where data is constantly changing, such as an e-commerce website. Next.js offers incremental static regeneration to solve this problem.
Incremental Static Regeneration — Next.js lets you create or update static pages after you have built your website. By using the ‘revalidate’ prop, we can regenerate certain website pages after a certain period of time. Let us see how we can do that.
In the above example, we have set ‘revalidate’ to 5 seconds. This means this page will be regenerated after 5 seconds on request. After 7.51 seconds I refreshed the page (regeneration begins) but still the cached page is being served and when I refresh again regenerated page is served. Until the regeneration succeeds cached page with stale data is served.
Conclusion
In this blog we learnt about file-based routing, Link component, Head component, Pre-rendering and Data Fetching in Next.js. After this you can learn to work with APIs and authentication using next-auth and then you will be ready to develop production level applications.