Getting Started With Next.js and Create Your First Application Using Next.js

Prionto Abdullah
9 min readJan 5, 2021

Next.js provides a solution to all of the commonly faced problems during development with React.js. But more importantly, it puts you and your team in the pit of success when building React applications.

Next.js has the best-in-class “Developer Experience” and many built-in features;

To name a few of them:

  • 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 optimized prefetching
  • Built-in CSS and Sass support, and support for any CSS-in-JS library
  • Development environment which supports Hot Module Replacement
  • API routes to build API endpoints with Serverless Functions
  • Fully extendable

This is among the primary reason why Next.js is used in tens of thousands of production-facing websites and web applications, including many of the world’s largest brands.

Lets see the NEXT.js in action by setting up a quick app to demonstrate basic along with a few advanced functionalities..

Development ENV Setup

  • You will need to have Node.js version 10.13 or higher installed on your system to proceed. You can install it from here, in case you don’t have already.
  • VS-Code, or any editor of your choice.

Creating a Next.js app

To create a Next.js app, open your terminal, cd into the directory you’d like to create the app in, and run the following command:

npm init next-app nextjs-blog --example "https://github.com/zeit/next-learn-starter/tree/master/learn-starter"

Behind the scene you are instructing npm to initialize a new next app within nextjs-blog folder. This basically uses the tool called create-next-app,
which bootstraps a Next.js app for you.
It uses
this template through the --example flag.
If it doesn’t work, please take a look at
this page.

Once this command completes you will see a new folder created with name nextjs-blog.

Running the app

Let’s cd into your newly created folder by using the following command:

cd nextjs-blog

Then, run the following command:

npm run dev

This starts your Next.js app’s “development server” on port 3000.
Open http://localhost:3000 from your browser to see it in action.

If everything goes as expected you will see the following screen in your browser:

Output screen after running the app

The Next.js development server has the Hot Reloading feature. When you make changes to files Next.js automatically applies the changes in the browser. No refresh needed! This will help you iterate on your app quickly.

Creating Pages

In Next.js, a page is a React Component exported from a file in the pages directory.

All pages are associated with a route based on their file name by default.

  • pages/index.js is associated with the / route.
  • pages/users.js is associated with /users route. Similarly,
  • pages/posts/first-post.js is associated with the /posts/first-post route.

Go ahead and try adding some by urself and see how it reacts. Once done you can proceed to next section.

Manual Routing in Next.js

When linking between pages on websites you generally use the <a> HTML tag.

In Next.js, you use the <Link> React Component that wraps the <a> tag. <Link> allows you to do client-side navigation to a different page in the application.

Lets see it in action:

First, in pages/index.js, import the Link component from next/link by adding this line at the top:

import Link from 'next/link'

Then modify this line in the h1 tag to look like this:

Read <Link href="/posts/first-post"><a>this page!</a></Link>

Considering you have created a first-post.js as suggested above, lets replace the content with the following.

import Link from 'next/link'export default function FirstPost() {
return (
<div>
<h1>First Post</h1>
<p>Hey there, I am a newly created Post.</p>
<br/>
<h2>
<Link href="/">
<a>Navigate to home</a>
</Link>
</h2>
</div>
)
}

As you can see, the Link component is similar to using <a> tags, but instead of <a href="…">, you use <Link href="…"> and put an <a> tag inside.

Let’s check to see it works. You now should have a link on each page, allowing you to go back and forth:

navigating between pages

A few quick notes about navigation:

  • Client-side navigation means that the page transition happens using JavaScript, which is faster than the default navigation done by the browser.
  • If you’ve used <a href="…"> instead of <Link href="…"> and did this, the browser does the full refresh. but in our case it’s not the case.

If you want to ensure this, use the browser’s developer tools to change the background CSS property of <html> to blue. Click on the links to go back and forth between the two pages. You’ll see that the blue background persists between page transitions. This ensures we are not reloading the page actually.

Code splitting and prefetching

Next.js does code splitting automatically, so each page only loads what’s necessary for that page. That means when the homepage is rendered, the code for other pages is not served initially.

This ensures that the homepage loads quickly even if you add hundreds of pages.

Only loading the code for the page you request also means that pages become isolated. If a certain page throws an error, the rest of the application would still work.

Furthermore, in a production build of Next.js, whenever Link components appear in the browser’s viewport, Next.js automatically prefetches the code for the linked page in the background. By the time you click the link, the code for the destination page will already be loaded in the background, and the page transition will be near-instant!

Next.js is the powerful react framework that solves different problems like Server Side Rendering, Pre-rendering, SEO, etc. But it always keeps you very close with awesome library — react to develop your application. Next.js is bundled with plenty of built-in classes for better Developer Experience like:

  • Page based routing system (with support to custom routing)
  • Pre-rendering, both static generation and server side rendering
  • Client-side routing with optimized prefetching
  • Built-in CSS and Sass support
  • Development Environment which supports hot module replacement

Next.js has been trusted by the very big companies in the world. If you are from the react background, then you will find almost everything similar to react while using Next.js. Today, in this article, we will be developing a very simple Next.js application with some design and layouts and we will fetch api using pre-rendering.
Let’s build the app then!

1. Create Project Directory
Let’s create a project directory and name it as hello_next. Open up the project directory on your favorite Code Editor and I would prefer vscode for it.

2. Initialize package.json
Open up the terminal containing the project directory and run following command that will create package.json file, which includes our project dependencies and scripts. Including -y on the command will generate the package file with all the defaults.

npm init -y

3. Install React, React Dom and Next
Now, we install React, React Dom and Next for our project with the following command.

npm install --save react react-dom next

3. Change Scripts of package.json
Add these scripts to the scripts section of package.json. Then, we can run the code with the command npm run dev.

//package.json"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},

4. Routing
Next.js has file-system based router built on concept of pages. So, we need to create a folder named pages and whatever the name of the file would be, the same would be the name of route. You will know better about it when we make use of this concept.
We will be creating two pages, one would be the home page and another would be about page.
So, let’s create index.js file inside the pages directory with simple welcome text.

//pages/index.jsconst Index = () => {
return (
<div>
<h1>Welcome to Next Application</h1>
</div>
);
}export default Index;

Now, create about.js file inside same pages directory with following code.

//pages/about.jsconst About = () => {
return(
<div>
<h1>
About NextJS
</h1>
<p>Application to Demonstrate NextJS Basics</p>
</div>
);
}export default About;

If you haven’t run the project yet, then run with npm run dev command. you will see the home page because index.js will take ‘/’ route. For now add ‘/about’ to the url to navigate to about page. We will build a navigation sections with bootstrap later on.

Home Page
About Page

5. Components
We can create the components in Next.js same as of react. So, let’s create Navbar component and the Layout component which includes layout of our simple demo application.
First, let’s create the Navbar Component. So, we create folder named components to the root of the project. Inside components folder, create navbar.js file which includes navigation menu for the project and also include bootstrap CDN for better design. Also, we are going to implement styled jsx just to demonstrate how they are used in next.js. These styles would be available to only this component.

//components/navbar.jsimport Link from 'next/link';const Navbar = () => {
return(
<div>
<ul>
<li><Link href="/"><a>Home</a></Link></li>
<li><Link href="/about"><a>About</a></Link></li>
</ul><style jsx>{`
ul {
background: #333;
color: #fff;
list-style: none;
display: flex;
}ul li {
font-size: 22px;
margin-right: 50px;
}ul li a {
color: #fff;
text-decoration: none;
}
`}</style>
</div>
);
}export default Navbar;

You can see how router navigation is done with next/link in the above code.
Now, we need to create a layout for the project. So, we will create layout.js file inside the components folder and we will use the navbar component in layouts.

//components/layout.jsimport Head from 'next/head';
import Navbar from './navbar';
const Layout = (props) => {
return(
<div>
<Head>
<title>Hello Next.js</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
</Head>
<Navbar />
<div className="container">
{props.children}
</div>
</div>
);
}
export default Layout;

Now, lets modify our index.js and about.js to make use of the available layout.
We are going to apply very important feature of Next.js, which is `getInitialProps`. getInitialProps enables server-side rendering in a page and allows us to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. It is an async function that can be added to any page as a static method. Let’s take a look at how we are going to fetch data for sample music api and display them in our home page. Also, we are going to add isomorphic-unfetch to fetch the api.

npm install --save isomorphic-unfetch

After adding this let’s modify our index.js. The full and final code in this page is done below.

//pages/index.jsimport Layout from '../components/layout';
import fetch from 'isomorphic-unfetch';const Index = ({musicData}) => {
console.log(musicData)
return (
<Layout>
<div>
<h1>Welcome to Next Application</h1>
<h3>Songs List</h3>
{musicData.map((item, i) => {
return (
<li key={i}>{item.title}</li>
)
})}
</div>
</Layout>
);
}Index.getInitialProps = async function() {
const response = await fetch(`https://www.what-song.com/api/recent-movies`);
const result = await response.json();
return { musicData: result.data }
}export default Index;

Also, let’s modify our about.js. The full and final code in this page is done below.

//pages/about.jsimport Layout from '../components/layout';const About = () => {
return(
<Layout>
<div>
<h1>
About NextJS
</h1>
<p>Application to Demonstrate NextJS Basics</p>
</div>
</Layout>
);
}export default About;

Demo

Now, our very simple Next.js application is ready to run. You can find the data fetched through the sample api and the pages as shown below:

Home page with list of songs
About page

Summary

Next.js automatically optimizes your application for the best performance by code splitting, client-side navigation, and prefetching (in production).This is very simple application developed using Next.js. You can gain the basic knowledge about how to install and work with next.js through this article.

You create routes as files under pages and use the built-in Link component. No routing libraries are required.

You can learn more about the Link component in the API reference documentation and routing in general in the routing documentation.

--

--

Prionto Abdullah

Become a world’s no 1 full-stack web developer. That’s why I am learning and mastering web development. I will not stop until I become the Web Development Hero.