Building (or cloning) a JavaScript-based app using React as the front-end framework comes with some challenges. You want to focus on building and shipping the application rather than spending too much time configuring, code-splitting, determining content loading architecture, and bundling it all together in order to serve it as a web application.

Welcome, Next.js!

I appreciate Next.js as a React framework because it addresses the above-mentioned problems and is, more or less, a zero-configuration framework for React applications. For example, when you are releasing a public app or a website, you need to render the content so that search engines can index your website. Next.js tends to solve this common challenge by handling server-side rendering for you.

In this tutorial, we are going to build a small Hacker News React app using the Next.js framework. By completing this tutorial, you will have experience with setting up and building an app with Next.js, and you will hopefully also get a feel for just how much it handles for you, out of the box.

In this tutorial, we’ll cover:

Getting Started with Next.js

Building a ‘Hello World’ App

Creating pages

Routing in Next.js

Building a Real Time App (a mini Hacker News clone)

Fetching data from third party api

Significant use of getInitialProps in any Next.js app

in any Next.js app Built-in components like Link , Error , and Head

, , and Learn how to use styled-jsx to style Next applications

to style Next applications Implement Pagination using a third party API and query parameters

⚙️ Pre-requisites

To continue with this tutorial, you will need the following:

npm installed on your machine.

installed on your machine. Knowledge of ES6 JavaScript features such anonymous arrow functions => , import and export statements, async/await and so on.

, and statements, and so on. React itself

First Universal JavaScript App

A Next.js project can be easily initialized using npm .

Create a new directory, traverse inside it, and install the following dependencies.

The next step is to edit the package.json file with following scripts .

If you run the command npm run dev now, there will be an error stating that there is a missing pages folder. The name of this folder is significant, which we will discuss later. For right now, create a new folder pages in the root of your project and inside create a new file called index.js with the following content.

The file-system of your project is the main API that Next uses to serve on the client. Every .js file becomes a route and gets rendered.

Now run the npm run dev command from your terminal and go to URL http://localhost:3000/ to see the following result.

Note that you can define your own port as a command line option when running the dev script. npm run dev -- -p <your port here> . 3000 is the default port used by Next when there is no custom port number defined.

Now, in a typical React project, you might have webpack to bundle your component files, or in our case pages/index.js and use Babel to transpile the JavaScript/JSX code inside it. Next does this automatically for you. Another important aspect to notice here is that Next uses Hot Code Reloading when in development mode. Any changes you make inside index.js file are going to be automatically reflected in the browser window.

Creating Pages

The pages directory here is the routing system Next uses. There is no need for react-router or any other routing library integration. Now let us add another page. Create a new file called second.js with the following content.

This page can be simply accessed using the URL http://localhost:3000/second . You can even have sub-directories and use them as a normal route. For example, create a new sub-directory inside pages/crypto/index.js with a file and the following code.

To see this in action, visit the URL http://localhost:3000/crypto and see the following message in the browser window.

Another thing to notice here is that we are not using the import React... statement in crypto/index.js file. You can use anything from React in Next without having to import it. Next has its own presets when compiling the code and adds that for you. If you want to see how it does that, you will notice that in your project there is a hidden directory called .next . Visit this path: .next/static/development/pages/crypto to view how Next is rendering our routes behind the scene. You will also notice it uses Webpack.

Routing in Next.js

Now we have three pages in the Next.js project.

In this section, I’ll show you how to do a proper client-side navigation in Next.js that is SEO friendly. In order to support client-side navigation, let us use Next.js’ Link API, which is exported via next/link .

Edit both index.js and second.js files like below in order to make this recipe work.

In the above code snippet, notice that the href attribute is used on Link rather than <a> tag. This is the Next.js way of doing things. Also, using anchor tag inside <Link> makes it SEO friendly.

You can verify the results below.

🚀 Building a Real Time App

So far we have covered (some of) the basics of Next.js.

From this section onwards, you are going to build a real-time application using Next.js and apply the routing knowledge you just learned.

You are going to build a Hacker News clone using the Y Combinator Hacker News API. Along the way, you’ll learn an important concept of using APIs in a Next.js application. Let’s get started!

Initializing the Project

You can start a new project and follow the same procedure of initializing it with npm and installing the required dependencies. Once you have done that, create the pages/ directory and add a home page in a file called index.js . Run the npm run dev command and see if everything is working fine.

Now, let’s install a dependency that is going to make AJAX requests to the Hacker News API to fetch stories and help us display them through our own custom React components. Install the following package from your terminal.

Why are we using this package instead of the fetch API that comes with latest JavaScript or even a more popular module like axios that is common in React community?

The fetch API is a just a polyfill for browsers which do not have it available as a function yet. The fetch API adds the function itself to the window object of your browser. The package you are going to use isomorphic-fetch is an implementation of fetch for both the server (the Node.js part) and the browser build up on that polyfill.

Fetching Data from the API

Now, let us fetch those stories from the API. For our demo purpose, I am going to use an open-source API called node-HNAPI. Edit the index.js file by importing fetch from isomorphic-fetch , creating a class component from React.Components and initializing the props in order to fetch the stories.

To load data when the home page of the application loads, in Next.js we use, getInitialProps which is an async method. This means, it can fetch the data required asynchronously and resolves the result or response object in the case above into a plain JavaScript object that populates React's props . Data returned from getInitialProps is serialized when server rendering, similar to a JSON.stringify .

One thing to remember here is that, in any Next app, you can only use getInitialProps in a file that exists inside the pages/ directory. It cannot be used with children components.

Using try/catch block, we are fetching stories from the API URL https://node-hnapi.herokuapp.com/news?page=1 . The significance of using try/catch will become clear to you later as we are going to deliberately cause an error in the app and hook a way to handle it.

Lastly, the render function gets stories from this.props and using JavaScript's map we can query on the array which currently holds the data to display it on the screen. Try running the npm run dev command and see the following result like below.

Using built-in Error Page

Next.js provides a built-in error page to display to the user in a case when there is a problem fetching the data from the API. This is available through Error Component from next/error and can be used directly in the code. Modify the index.js file like below.

In the above snippet, the API link is not correct. It will not fetch the data and instead show a weird error that is recommended not to be shown on the client side because the end user doesn’t care about the specific error. That is for us to handle. Changing the previously working API URL to error-causing non-functional URL: https://node-hnapi.herokuapp.com/abs , is handled in the render function using the built-in Error component as shown above.

Do take a note that, we are passing an empty array to stories in the catch block to check if the stories are unavailable due to some reason, we can display the following to the end user.

After this step, leave out the built-in error part but change the API URL back to https://node-hnapi.herokuapp.com/news?page=1 and things will start working again.

Using Components in Next.js

Using re-usable components in Next.js is completely identical to how you would do the process in any React application. This certainly clarifies the beginner doubts related to Next.js is all about pages. Let’s build one for ourselves.

Create a new directory in the root of the project and name it components . Inside it, create a new component StoryList.js with the following code.

This component receives all stories from the page index.js as props. To make this work, you will have to import this component inside index.js and pass stories that are being fetched from the API as props .