Next.js – Imperitive Routing

Next.js – Imperative Routing ”; Previous Next 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 Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Click on First post which is not a link but is clickable. Print Page Previous Next Advertisements ”;

Next.js – Environment Variables

Next.js – Environment Variables ”; Previous Next 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 } } } Now start the server. Next.JS will detect .env.local and show follwing message on console. npm run dev > [email protected] dev D:Nodenextjs > next ready – started server on http://localhost:3000 info – Loaded env from D:Nodenextjs.env.local event – compiled successfully wait – compiling… event – compiled successfully event – build page: /posts/env wait – compiling… event – compiled successfully Verify Output Open localhost:3000/posts/env in a browser and you will see the following output. Print Page Previous Next Advertisements ”;

Next.js – Shallow Routing

Next.js – Shallow Routing ”; Previous Next 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(”/?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 Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and then click on Reload link and you will see the following output. Print Page Previous Next Advertisements ”;

Next.js – Pre-Rendering

Next.js – Pre-Rendering ”; Previous Next In Next.js, we know 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. Let”s create an example to demonstrate the same. In this example, we”ll create a 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 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 } } } Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Click on First post link. Print Page Previous Next Advertisements ”;

Next.js – Overview

Next.js – Overview ”; Previous Next The Next.js is React Based framework with server side rendering capability. It is very fast and SEO friendly. Using Next.js, you can create robust react based application quite easily and test them. Following are 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. Print Page Previous Next Advertisements ”;

Next.js – API MiddleWares

Next.js – API MiddleWares ”; Previous Next 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 })) } Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev D:Nodenextjs > next ready – started server on http://localhost:3000 info – Loaded env from D:Nodenextjs.env.local event – compiled successfully event – build page: /api/user wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open http://localhost:3000/api/user?counter=1 in a browser and you will see the following output. {“query”:{“counter”:”1″}} Print Page Previous Next Advertisements ”;

Next.js – Pages

Next.js – Pages ”; Previous Next In Next.js, we can create pages and navigate between them using file system routing feature. We”ll 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. pages/posts/first.js is linked with ”/posts/first” route and so on. Let”s update the nextjs project created in Environment Setup chapter. Create post directory and first.js within it with following contents. export default function FirstPost() { return <h1>My First Post</h1> } Add Link Support to go back to Home page. Update first.js as follows − import Link from ”next/link” export default function FirstPost() { return ( <> <h1>My First Post</h1> <h2> <Link href=”/”> <a>Home</a> </Link> </h2> </> ) } Add Link Support to home page to navigate to first page. Update index.js as follows − import Link from ”next/link” function HomePage() { return ( <> <div>Welcome to Next.js!</div> <Link href=”/posts/first”><a>First Post</a></Link> </> ) } export default HomePage Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Click on First Link and you will see the following output. Print Page Previous Next Advertisements ”;

Next.js – Environment Setup

Next.js – Environment Setup ”; Previous Next As Next.js is a react based framework, we are using Node environment. Now make sure you have Node.js and npm installed on your system. You can use the following command to install Next.js − npm install next react react-dom You can observe the following output once Next.js is successfully installed − + [email protected] + [email protected] + [email protected] added 831 packages from 323 contributors and audited 834 packages in 172.989s Now, let”s create a node package.json − npm init Select default values while creating a package.json − This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (nextjs) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC) About to write to Nodenextjspackage.json: { “name”: “nextjs”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “dependencies”: { “next”: “^9.4.4”, “react”: “^16.13.1”, “react-dom”: “^16.13.1″ }, “devDependencies”: {}, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “author”: “”, “license”: “ISC” } Is this OK? (yes) Now update the scripts section of package.json to include Next.js commands. { “name”: “nextjs”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “dependencies”: { “next”: “^9.4.4”, “react”: “^16.13.1”, “react-dom”: “^16.13.1″ }, “devDependencies”: {}, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″, “dev”: “next”, “build”: “next build”, “start”: “next start” }, “author”: “”, “license”: “ISC” } Create pages directory. Create a pages folder within nextjs folder and create an index.js file with following contents. function HomePage() { return <div>Welcome to Next.js!</div> } export default HomePage Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Print Page Previous Next Advertisements ”;

Next.js – Meta Data

Next.js – Meta Data ”; Previous Next In Next.js, we can serve modify the head section of each react pages very easily with the help of <Head> react component which is inbuilt. Let”s update the nextjs project used in Pages chapter. Update index.js as follows − import Link from ”next/link” import Head from ”next/head” function HomePage() { 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/> <img src=”/logo.png” alt=”TutorialsPoint Logo” /> </> ) } export default HomePage Update first.js as follows − import Link from ”next/link” import Head from ”next/head” export default function FirstPost() { return ( <> <Head> <title>My First Post</title> </Head> <h1>My First Post</h1> <h2> <Link href=”/”> <a>Home</a> </Link> </h2> </> ) } Here we”ve added a reference to logo.png in index.js file. Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Click on First Page link and verify the title changed in First Post page as well. Print Page Previous Next Advertisements ”;

Next.js – Home

Next.js Tutorial PDF Version Quick Guide Resources Job Search Discussion The Next.js is React Based framework with server side rendering capability. It is very fast and SEO friendly. Using Next.js, you can create robust react based application quite easily and test them. Audience This tutorial is designed for software programmers who want to learn the basics of Next.js and its concepts in a simple and easy manner. This tutorial will give you enough understanding on the various functionalities of Next.js with suitable examples. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of JavaScript and React. Print Page Previous Next Advertisements ”;