Key Features Of Next.Js

The key features of Next.js.

  • Hot Code Reload − Next.js server detects modified files and reloads them automatically.
  • Automatic Routing − No need to configure any url for routing. files are to be placed in pages folder. All urls will be mapped to file system. Customization can be done.
  • Component specific styles − styled-jsx provides support for global as well as component specific styles.
  • Server side rendering − react components are prerendered on server hence loads faster on client.
  • Node Ecosystem − Next.js being react based gels well with Node ecosystem.
  • Automatic code split − Next.js renders pages with libraries they need. Next.js instead of creating a single large javascript file, creates multiples resources. When a page is loaded, only required javascript page is loaded with it.
  • Prefetch − Next.js provides Link component which is used to link multiple components supports a prefetch property to prefetch page resources in background.
  • Dynamic Components − Next.js allows to import JavaScript modules and React Components dynamically.
  • Export Static Site − Next.js allows to export full static site from your web application.
  • Built-in Typescript Support − Next.js is written in Typescripts and provides excellent Typescript support.

Create pages directory.

Key features of Next.js Tutorial Image 1

Verify Output

Open localhost:3000 in a browser and you will see the following output.

Key features of Next.js Tutorial Image 2

Next.js - Pages

- Create pages and navigate between them using file system routing feature.

- Use Link component to have a client side navigation between pages.

In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name. For example

  • pages/index.js is linked with '/' route.
  • first.js is linked with 'first' route and so on.

Key features of Next.js Tutorial Image 3

Verify Output

Open localhost:3000 in a browser and you will see the following output.

Key features of Next.js Tutorial Image 4

Click on first page

Key features of Next.js Tutorial Image 5

Land on first page

Click on home land on home page

Click on about post land on about page

Key features of Next.js Tutorial Image 6

Next.js - Static File Serving

- serve static pages like images very easily by putting them in public, a top level directory. We can refer these files in similar fashion like pages in pages directory.

- In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name.

- Create public directory and place any images within it. We've taken logo.png, any Logo image.

output

Key features of Next.js Tutorial Image 7

Next.js - Meta Data

- serve modify the head section of each react pages very easily with the help of <Head> react component which is inbuilt.

Key features of Next.js Tutorial Image 8

Output:

Key features of Next.js Tutorial Image 9

Next.js - CSS Support

- use inbuild css-in-js library named styled-jsx. It allows to write css within a react component and these styles will be scoped to component.

- create a Container object which will be used to style other components by containing them.

- First create a Components directory at root level and add a file container.module.css as follow

Key features of Next.js Tutorial Image 10

Create container.js file in Components directory

Key features of Next.js Tutorial Image 11

Now use Container component in first.js.

Key features of Next.js Tutorial Image 12

Verify Output

Open localhost:3000 in a browser and go to first post, you will see the following output.

Key features of Next.js Tutorial Image 13

Next.js - Global CSS Support

- create global styles which will be applied on all pages.

- create a styles.css which will be used on all components using _app.js component.

First create a styles directory at root level and add a file

Key features of Next.js Tutorial Image 14

Create _app.js file in pages directory

Key features of Next.js Tutorial Image 15

Verify Output

Open localhost:3000 in a browser and you will see the following output.

Key features of Next.js Tutorial Image 16

Key features of Next.js Tutorial Image 17

Next.js - Pre-Rendering

It generates HTML for a page called pre-rendering. Next.JS supports two types of pre-rendering.

  • Static Generation − This method generates the HTML page at build time. This pre-rendered HTML is sent on each request. This method is useful for marketing websites, blogs, e-commerce products listing wesites, helps, documentation websites.
  • Server Side Generation − This method generates the HTML page on each request. This method is suitable when an html page contents can vary with each request.

Per Page Pre-rendering

Next.JS allows to set pre-rendering method for each page where most of pages follow static generation and other pages will use server side rendering.

Static Generation Without Data

Static generation can be done without data in which case, HTML pages will be ready without need to prefetch the data and then start rendering. Data can be fetched later or on request. This technique helps in showing user an User Interface without any data in case data takes time to come.

Static Generation With Data

Static generation can be done with data in which case, HTML pages will not be ready until data is fetched, as HTML may be dependent on data. Each component has a special method getStaticProps which can be used to fetch data and pass data as props of the page so that page can render accordings to passed props.

getStaticProps() function runs at build time in production and runs for every request in dev mode.

Update index.js file in pages directory to use getServerSideProps() method. This method will be called per request.

{`

import Link from 'next/link'

import Head from 'next/head'

function HomePage(props) {

return (

<>

<Head>

<title>Welcome to Next.js!</title>

</Head>

<div>Welcome to Next.js!</div>

<Link href="/posts/first"><a>First Post</a></Link>

<br/>

<div>Next stars: {props.stars}</div>

<img src="/logo.png" alt="TutorialsPoint Logo" />

</>

)

}

export async function getServerSideProps(context) {

const res = await fetch('https://api.github.com/repos/vercel/next.js')

const json = await res.json()

return {

props: { stars: json.stargazers_count }

}

}

export default HomePage

`}

Update first.js file in pages directory to use getStaticProps() method. This method will be called once.

{`

import Link from 'next/link'

import Head from 'next/head'

import Container from '../../components/container'

export default function FirstPost(props) {

return (

<>

<Container>

<Head>

<title>My First Post</title>

</Head>

<h1>My First Post</h1>

<h2>

<Link href="/">

<a>Home</a>

</Link>

<div>Next stars: {props.stars}</div>

</h2>

</Container>

</>

)

}

export async function getStaticProps() {

const res = await fetch('https://api.github.com/repos/vercel/next.js')

const json = await res.json()

return {

props: { stars: json.stargazers_count }

}

}

`}

Verify Output

Open localhost:3000 in a browser and you will see the following output.

Key features of Next.js Tutorial Image 18

Key features of Next.js Tutorial Image 19

Next.js – Routing

Next.js uses file system based router. Add any page to pages directory, it is automatically available via url. Following are the rules of this router.

  • Index Routes − An index.js file present in a folder maps to root of directory. For example −

o pages/index.js maps to '/'.

o pages/posts/index.js maps to '/index.

  • Nested Routes − Any nested folder structure in pages directory because router url automatically. For example −

o pages/settings/dashboard/about.js maps to '/settings/dashboard/about'.

o pages/posts/first.js maps to '/posts/first'.

  • Dynamic Routes − We can use named parameter as well to match url. Use brackets for the same. For example −

o pages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'.

o pages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'.

o pages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'.

Page Linking

Next.JS allows to link pages on client side using Link react component. It has following properties −

  • href − name of the page in pages directory. For example /posts/first which refers to first.js present in pages/posts directory.

Let's create an example to demonstrate the same.

In this example, we'll update index.js and first.js page to make a server hit to get data.

Let's update the nextjs project used in Global CSS Support chapter.

Update index.js file in pages directory as following.

{`
import Link from 'next/link'
import Head from 'next/head'
function HomePage(props) {
 return (
 <>
 <Head>
 <title>Welcome to Next.js!</title>
 </Head>
 <div>Welcome to Next.js!</div>
 <Link href="/posts/first">> <a>First Post</a></Link>
 <br/>
 <div>Next stars: {props.stars}</div>
 <img src="/logo.png" alt="TutorialsPoint Logo" />
 </>
 )
}
export async function getServerSideProps(context) {
 const res = await fetch('https://api.github.com/repos/vercel/next.js')
 const json = await res.json()
 return {
 props: { stars: json.stargazers_count }
 }
}
export default HomePage
`}

output:

Key features of Next.js Tutorial Image 20

Key features of Next.js Tutorial Image 21

Next.js - Dynamic Routing

Create routes dynamically. Create pages on the fly and their routing.

  • Step 1. Define [id].js file − [id].js represents the dynamic page where id will be relative path. Define this file in pages/post directory.
  • Step 2. Define lib/posts.js − posts.js represents the ids and contents. lib directory is to be created in root directory.

[id].js

Update [id].js file with getStaticPaths() method which sets the paths and getStaticProps() method to get the contents based on id.

{`

import Link from 'next/link'

import Head from 'next/head'

import Container from '../../components/container'

import { getAllPostIds, getPostData } from '../../lib/posts'

export default function Post({ postData }) {

return (

<Container>

{postData.id}

<br />

{postData.title}

<br />

{postData.date}

</Container>

)

}

export async function getStaticPaths() {

const paths = getAllPostIds()

return {

paths,

fallback: false

}

}

export async function getStaticProps({ params }) {

const postData = getPostData(params.id)

return {

props: {

postData

}

}

}

`}

AD

posts.js

posts.js contains getAllPostIds() to get the ids and getPostData() to get corresponding contents.

{`

export function getPostData(id) {

const postOne = {

title: 'One',

id: 1,

date: '7/12/2020'

}

const postTwo = {

title: 'Two',

id: 2,

date: '7/12/2020'

}

if(id == 'one'){

return postOne;

}else if(id == 'two'){

return postTwo;

}

}

export function getAllPostIds() {

return [{

params: {

id: 'one'

}

},

{

params: {

id: 'two'

}

}

];

}

`}

Output:

Key features of Next.js Tutorial Image 22

Key features of Next.js Tutorial Image 23

Next.js - Imperative Routing

In Next.js, so far we are using Link react component to navigate from one page to other. There is a programmatic way as well to achive the same using Router component. Generally Router component is used with html tags.

Update index.js file in pages directory as following.

{`
import Router from 'next/router'
import Head from 'next/head'
function HomePage(props) {
 return (
 <>
 <Head>
 <title>Welcome to Next.js!</title>
 </Head>
 <div>Welcome to Next.js!</div>
 <span onClick={() => Router.push('/posts/one')}>First Post</span>
 <br/>
 <div>Next stars: {props.stars}</div>
 <img src="/logo.png" alt="TutorialsPoint Logo" />
 </>
 )
}
export async function getServerSideProps(context) {
 const res = await fetch('https://api.github.com/repos/vercel/next.js')
 const json = await res.json()
 return {
 props: { stars: json.stargazers_count }
 }
}
export default HomePage
`}

Verify Output

Open localhost:3000 in a browser and you will see the following output.

Key features of Next.js Tutorial Image 24

Key features of Next.js Tutorial Image 25

Next.js - Shallow Routing

In Next.js, shallow routing refers to navigating to same page but no calls to getServerSideProps, getStaticProps, and getInitialProps methods.

To do shallow routing, we use Router with shallow flag as true. See the below example.

Update index.js file in pages directory as following.

import Router from 'next/router'
import Head from 'next/head'
function HomePage(props) {
 return (
 <>
 <Head>
 <title>Welcome to Next.js!</title>
 </Head>
 <div>Welcome to Next.js!</div>
 <span onClick={() => Router.push('https://api.github.com/?counter=1', undefined, { shallow: true })}>Reload</span>
 <br/>
 <div>Next stars: {props.stars}</div>
 <img src="/logo.png" alt="TutorialsPoint Logo" />
 </>
 )
}
export async function getServerSideProps(context) {
 const res = await fetch('https://api.github.com/repos/vercel/next.js')
 const json = await res.json()
 return {
 props: { stars: json.stargazers_count }
 }
}
export default HomePage

Verify Output

Open localhost:3000 in a browser and then click on Reload link and you will see the following output.

Key features of Next.js Tutorial Image 26

Next.js - Api Routes

API Routes is a way to create rest API using Next.js. Next.js maps any file present in /pages/api folder and will be treated as API end point. An example of API function −

{`
export default (req, res) => {
 ...
}
`}

Following are some important points to consider.

  • req − req is an instance of http.IncomingMessage and is used to get data from request.
  • res − res is an instance of http.ServerResponse and is used to send data as response.

Let's create an example to demonstrate the same.

In this example, we are going to create an user.js in pages/api directory.

Let's update the nextjs project used in Global CSS Support chapter.

Create user.js file in pages/api directory as following.

{`
export default (req, res) => {
 res.statusCode = 200
 res.setHeader('Content-Type', 'application/json')
 res.end(JSON.stringify({ name: 'Robert' }))
}
`}

Verify Output

Open localhost:3000/api/hello in a browser and you will see the following output.

Key features of Next.js Tutorial Image 27

Next.js - API MiddleWares

API Routes in Next.JS have built-in middlewares which helps in parsing the incoming request.

Following are the middlewares

  • req.cookies − cookies object contains the cookies sent by the request. Default value is {}.
  • req.query − query object contains the query string. Default value is {}.
  • req.body − query object contains the request body parsed using 'content-type'. Default value is null.

Let's create an example to demonstrate the same.

In this example, we are going to update an user.js in pages/api directory.

Let's update the nextjs project used in API Routes chapter.

Create user.js file in pages/api directory as following.

{`
export default (req, res) => {
 res.statusCode = 200
 res.setHeader('Content-Type', 'application/json')
 res.end(JSON.stringify({ query: req.query }))
}
`}

Verify Output

Open http://localhost:3000/api/user?counter=1 in a browser and you will see the following output.

Key features of Next.js Tutorial Image 28

Next.js - Response Helpers

res object have express.js like helper methods to ease development to create services.

Following are the response helper methods

  • res.status(code) − This methods set the status of response. Code passed must be a valid HTTP status.
  • req.json(json) − This method returns a JSON response. json passed must be a valid JSON object.
  • req.send(body) − This methods sends an HTTP response. Response can be string, object or Buffer.

Let's create an example to demonstrate the same.

In this example, we are going to update an user.js in pages/api directory.

Let's update the nextjs project used in API Routes chapter.

Create user.js file in pages/api directory as following.

{`
export default (req, res) => {
 res.status(200).json({ name: 'Robert' });
}
`}

AD

Verify Output

Open http://localhost:3000/api/user in a browser and you will see the following output.

Key features of Next.js Tutorial Image 29

Next.js - TypeScript Support

Next.js, has execellent support for typescript. Following are few steps to enabling typescript in project.

Create tsconfig.json

Create tsconfig.json in root directory. We're keeping it empty initially. Now start the server.

Next.JS will detect tsconfig.json and show follwing message on console.

{`
npm run dev
> nextjs@1.0.0 dev D:\Node\nextjs
> next
ready - started server on http://localhost:3000
It looks like you're trying to use TypeScript but do not have the required package(s) installed.
Please install typescript, @types/react, and @types/node by running:
npm install --save-dev typescript @types/react @types/node
If you are not trying to use TypeScript, please remove the tsconfig.json file from your package root (and any TypeScript files).
...
`}

AD

Install typescript

Run the npm install command to install typescript and related libraries.

{`
npm install --save-dev typescript @types/react @types/node
...
+ @types/node@14.0.23
+ @types/react@16.9.43
+ typescript@3.9.6
added 5 packages from 72 contributors and audited 839 packages in 27.538s
...
`}

Start Next.js Server

npm run devAD

Open tsconfig.json

NextJS server has modified the tsconfig.json.

{`
{
 "compilerOptions": {
 "target": "es5",
 "lib": [
 "dom",
 "dom.iterable",
 "esnext"
 ],
 "allowJs": true,
 "skipLibCheck": true,
 "strict": false,
 "forceConsistentCasingInFileNames": true,
 "noEmit": true,
 "esModuleInterop": true,
 "module": "esnext",
 "moduleResolution": "node",
 "resolveJsonModule": true,
 "isolatedModules": true,
 "jsx": "preserve"
 },
 "exclude": [
 "node_modules"
 ],
 "include": [
 "next-env.d.ts",
 "**/*.ts",
 "**/*.tsx"
 ]
}
`}

Create hello.ts

Create hello.ts in pages/api directory which will acts as a rest service for us.

{`
import { NextApiRequest, NextApiResponse } from 'next'
export default (_: NextApiRequest, res: NextApiResponse) => {
 res.status(200).json({ text: 'Welcome to typescript‘ })
}
`}

Verify Output

Open localhost:3000/api/hello in a browser and you will see the following output.

30

Next.js - Environment Variables

Next.js, has support for publishing environment variables in node which we can use in connecting to server, database etc. For this, we need to create .env.local file in root directory. We can also create .env.production.

Create .env.local

Create .env.local in root directory with the following contents.

{`
DB_HOST=localhost
DB_USER=tutorialspoint
DB_PASS=nextjs
`}

Create env.js

Create a page named env.js with following contents in pages/posts directory where we'll use the environment variables using process.env.

{`
import Head from 'next/head'
import Container from '../../components/container'
export default function FirstPost(props) {
 return (
 <>
 <Container>
 <Head>
 <title>Environment Variables</title>
 </Head>
 <h1>Database Credentials</h1>
 <p>Host: {props.host}</p>
 <p>Username: {props.username}</p>
 <p>Password: {props.password}</p>
 </Container>
 </>
 )
}
export async function getStaticProps() {
 // Connect to Database using DB properties
 return {
 props: {
 host: process.env.DB_HOST,
 username: process.env.DB_USER,
 password: process.env.DB_PASS
 }
 }
}
`}

Output

Open localhost:3000/posts/env in a browser and you will see the following output.