Next.js Basics

Next.js  is a framework that builds up on react. it has more features than react, it focuses on more things than React and it gives us clear guides and rules on how we should write our code and structure our files.

React is a javascript library for building user interfaces. It’s a library because it focuses only on the user interface part containing the component, state, and props. For large-scale react projects you will need to add extra libraries for routing, authentication, and more.

Why Next.js?

  • Besides writing React code as we usually do, Next.js enhance react applications and adds more features
  • Next.js is a framework with built-in features such as routing and clear guidelines on how to use them.
  • Solves problems that we face with production-ready react applications.

Server Side Rendering

One of the important key features of Next.js is the server-side rendering support which means that instead of rendering the content of the page on the client it will render on the server.

When we inspect a page of a React application, we will see a simple HTML file with script tags. This page when served from the server will fetch the javascript code and then the JavaScript code will render the page content (HTML) inside an entry point element. This rendering happens on the client since react is a client-side JavaScript library.

Since the react application is loaded on the client there are a few drawbacks:

  • Initial Load: when there is for example a page that fetches data such as posts, there will be a small flickering page since the data will be fetched only when the JavaScript code is executed on the client.
  • SEO: the search engine crawlers don’t see any meaningful HTML content which means that the search engines won’t index the pages and we will have an SEO issue. 

Server-side rendering can help us with this issue since the pages and components are pre-rendered on the server and are served to the client with meaningful HTML content.

React has built-in features such as ReactDOMServer that can help us achieve server-side rendering but it is extra setup from our side and Next.js is much simpler since server-side is a built-in feature.

File-based Routing

Routing enables the navigation among views of various components by allowing us to make changes to the browser URL and keeps the UI in sync with the URL. it gives the user the illusion of multiple pages, 

Routing is not part of React and we have to use a library such as “React Router” to achieve routing in React applications. “React Router” watches the URL and when the URL changes it’s preventing the default behavior of the browser (which typically sends a request to a backend server) and renders different components on the page with React, usually these components sit in a different folder named “pages” which indicates the different routes.

With Next.js we define pages and routes with files and folders. We have a special folder named “pages” and by structuring this folder we define the routes and paths that the age supports.

Fullstack Applications

Next.js make it easy for us to add backend code to work with the computer’s internal feature such as the filesystem or the database by writing NodeJS code.

Create Next.js application

Creating a Next.js application is simple as creating a React app. All we have to do is to write the below code and we get the skeleton of the app:


npx create-next-app

To add a new page/route to the application, we have to add a new file with a name such as “blog.js” or add a folder named “blog” with a file inside named “index.js:


// Routing to http://my-website/articles will show the content of the component that is in the file articles.js
pages/articles.js

// Same result as above, will route to  http://my-website/articles and will show the content of the component that is in the file index.js
pages/articles/index.js

// Nested Routes: Routing to http://my-website/favorites/top-favorites will show the content of the component that is in the file top-favorites.js
pages/favorites/top-favorites.js

To create dynamic pages/routes we have to use brackets for the file name. let’s say that we have a route named “articles”, and we want to show in the “articles” page a specific articles such as “article 1” and “article 2” and so on. we will structure our folder and files like this:


pages/articles/index.js
pages/articles/[articleId].js

Inside the “[articleId].js” file we can use a special hook given to us by Next.js, this hook is the “useRouter” hook that gives us the identifier (the one inside the brackets). this identifier holds the concrete value in the URL for this dynamic segment for which this page was visited.

Let’s see how the “[articleId].js” file will look like:


import { useRouter } from 'next/router';

function DetailPage() {
   const router = useRouter();
   console.log(router.query.articleId);

   /* 
      TODO: Send a request to the backend API to fetch an the article with the id of 
      "router.query.articleId"
   */
   return <div>Details page of {router.query.articleId}</div>
}

export default DetailPage;

To create a menu with links to the articles we could create an anchor tag that will link to article1 for example like this: “<a href=’articles/article1’>article1</a>’. but when we will click this link the browser will send a request and a new HTML page will arrive in the browser which will prevent us from preserving the state across pages since it will be no longer a single-page application.

To overcome the above scenario we can use a special component provided to us by Next.js:


import Link from 'next/link';

function ArticlesPage() {
   return (
      <div>
         <ul>
            <li><Link href="/articles/article1">article 1</Link></li>
         <ul>
      </div>
   );
}

export default ArticlesPage;