Next JS Framework
Tags: agilewebandappdevelo
Published: 2022-01-25 13:20:41

---
title: Next JS Framework
published: true
date: 2022-01-18 16:27:50 UTC
tags: Agilewebandappdevelo
canonical_url: https://apiumhub.com/tech-blog-barcelona/next-js-framework/
---

This article is based on the [Next.js](https://nextjs.org/learn/basics/create-nextjs-app) documentation.

## What is Next JS?

Framework extensively used by react, used by [TikTok](https://www.tiktok.com/es/), [Twitch mobile](https://www.twitch.tv/), [Nike](https://www.nike.com/es/), [IGN](https://es.ign.com/), [PlayStation](https://www.playstation.com/es-es/), [Marvel](https://www.marvel.com/), among many others. It offers all the functionality we need to deploy our application in production, with a hybrid system with static pages and server-side rendered (SSR) pages. It has support for [Typescript](https://www.typescriptlang.org/), and can be deployed without having to configure anything.

## SSR Benefits (Next.js):

- Performance
- Isomorphic: Works on both server and client (browser)
- Build: Next.js in the build retrieves the necessary data and ejects html with react components.
- Static export: Compile static files to be able to upload to server
- 0 config (No need to configure anything to deploy next, however it has a very extensible config)
- Api routes
- Deploy with [Vercel](https://vercel.com/)
- Next head: To modify the `head` part of the page to improve the SEO
- [Typescript](https://www.typescriptlang.org/) support
- Environment variables are used in the browser code, not just server code.
- [Fast Refresh](https://nextjs.org/docs/basic-features/fast-refresh): New experience of `hot reloading` in react components
- Code splitting: loads chunk corresponding to page path

## Comparison with [Gatsby](https://www.gatsbyjs.com/)

Gatsby is primarily used for building web sites that generate static HTML content.  
It is used for web pages that have a fixed or predictable number of pages and their content will be stable.  
An example might be an ecommerce site that has only 50 products available for sale.

On the other hand, Next.js can also create page content statically, but adds the ability to create pages rendered to the server, both types can be combined.  
An example for Next.js would be a page that has a search engine with filters with thousands of results and combinations available.

Next needs a server, but Gatsby can run without this need.  
Next generates HTML/JS/CSS on `runtime` and Gatsby does it on `buildtime`.

We could add many more features of gatsby, but we will focus only on the main difference between these two frameworks.

## Comparison with [Express](https://expressjs.com/es/)

Express is a backend framework for node.js to build APIs.  
It has a robust routing and `http helpers` (redirection, cache…).

Next.js on its side also includes a routing system that can perfectly replace express.  
If we are building a private page, that we can only access with credentials and that does not have to be found by the `search engines`, you can use Express.  
On the contrary, if you are looking to build a public page with SEO, you should use Next.js.

## Building a Next.js project

The first thing we must do is to create our next project, and to do it we have used [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

```
npx create-next-app apiumhub
```

Like most js projects we can access the directory created and launch the project:

```
bash
npm run dev
# or
yarn dev
```

### Modifying web head data

As we have mentioned, Next.js is mainly used to be able to serve a web page with SSR and therefore, to be able to modify all the indispensable requirements to be able to improve the SEO and that the `search engines` can index our site.

For the SEO of a page it is very important to be able to edit the information of the `<title>`, the description, keywords etc., so next allows us to modify it in an easy way as we see below:

```
import Head from 'next/head'

<Head>
    <title>Apiumhub</title>
    <meta name="description" content="Welcome to Next.js" />
    <link rel="icon" href="/favicon.ico" />
</Head>
```

### Configuring the routes

Continuing with SEO, if we want to index different pages, we will have to create them and provide the individualized meta information to each one.  
To add a new route simply create inside `pages` a new file with the name of the route `blog.js` and add:

```
export default function Blog () {
  return <h1>This is the Apium blog</h1>
}
```

With this Next.js will automatically create this page with SSR so that it can be indexed.

### Navigation between pages

To navigate from our home page to our blog:

```
<a href='/blog'> Blog </a>
```

If we use ``<a></a>` we do not have a SPA (Single page application) but each page will be loaded again in our browser, to solve this and to be able to have a SPA (keeping also the SSR of the pages created) next offers us the following component:

```
import Link from 'next/link'

<Link href="/blog">Blog</Link>
```

If we come from react and we want to be able to use the router we are used to:

```
import { useRouter } from 'next/router

const router = useRouter()
router.replace('/')
```

![home](https://apiumhub.com/wp-content/uploads/2022/01/home.png "Next JS Framework 1")

![blog](https://apiumhub.com/wp-content/uploads/2022/01/blog.png "Next JS Framework 2")

### Initial props in server

With react we are used to pass properties to our components,  
but now our Home and Blog pages are SSR pages, so how can we pass props to our pages?

Next has the `getInitalProps` that we have to use as we see below:

```
Home.getInitialProps = () => {
    return { name: 'Apiumhub' }
}
```

This object will be the properties that come to our page. Here we can do a `fetch` and retrieve data from our API without any problem.

This method `getInitalProps` is executed in the server, when entering the route, next checks if there is a getInitialProps and executes it, being able to make a fetch, therefore it can also be `async` and it is going to wait until it finishes to render.

Apart from that, it will also run again in browser. Why is this?

We may think that this would not be necessary, since it has been rendered on server, but we need to have this information available so that react can hydrate our component and be able to render the same thing that has been rendered in server.

This data can be found in our HTML:

![html](https://apiumhub.com/wp-content/uploads/2022/01/html.png "Next JS Framework 3")

It is necessary to remark that in the last versions of Next they recommend us to use `getStaticProps` or `getServerSideProps` instead of `getInitalProps`, even that it would be very similar to what we have just seen, there is some small change that you can consult in the documentation of [Next.js](https://nextjs.org/learn/basics/create-nextjs-app).

![initialProps](https://apiumhub.com/wp-content/uploads/2022/01/initialProps.png "Next JS Framework 4")

### Important

`getInitialProps` only works on page-type components

## Curiosities

1. No need to import React, next imports it automatically, so we don’t have to import it every time.

```
import React from 'react'
```

2. For paths, next.js also interprets directories. Earlier we added blog.js so that it knows how to locate the path, but, if we create a blog folder with an index.js inside with the content of the previous blog.js page, it will work the same as we did before.

3. With a React app if we disable Javascript in the browser, and refresh, our application will not load, with next.js it will not only continue loading, but for example a `<Link>` would continue navigating since it ends up being a `<a>` for the browser and therefore everything is already rendered on the server.