Why you should use Next.js in all your React projects a Web3 developer

1 31
Avatar for Sage_Osoro
1 year ago

Now, traditional React apps are great, but because most are client-side rendered, it becomes difficult for search engine web crawlers to pick up useful information from your React source code. Come in Next.js, this is a React framework for building fast server-side rendering and static web applications. With Next, the raw source code of your React apps is readily available to be used by search engine web crawlers.

Next has gained popularity over the years and is widely used by companies looking to create highly efficient websites. The framework was created by Vercel, a popular frontend & web hosting platform that helps frontend developers easily push websites to production. Next is merely a technology for handling certain React tools and configurations. It should not be compared to frameworks like Angular or Vue.

In this article, we’ll be going through the key features of Next.js and why it is the perfect technology for you to add to your tech stack before going to production.

Benefits of using Next.js

  • Deploying your application to production is easier.

  • Your users can see pages of your website through search engines due to Next.js’ effective Search Engine Optimization (SEO) performance.

  • Next.js loads only the necessary JavaScript and CSS it needs for a certain page which in turn makes that page load faster.

  • API routes - You can easily create an API endpoint as a Node.js serverless function.

  • Easy page routing - Easily navigate between the pages of your application by creating JSX components in the pages folder.

  • Static Exports - You can easily export a fully static site from your application.

API Routes

In Next.js, API routes allow you to create and connect to an API endpoint easily. In your Next.js project under the “pages” folder, you will find a folder called “api”. Files stored in the “api” folder are treated as an API endpoint and not a page. The code written in this folder is never bundled with the frontend code and thus does not affect website speed. 

If you look into the "api" folder, you will find a file called “hello.js” which is an example file created by Next.js to show developers how easy it is to use API routes but you can delete this file and create your API route. First, let us see what is going on in “hello.js”:

export default function handler(req, res) {

    res.status(200).json({ name: 'John Doe' })

}

So to create a basic API route like the one above, we have to export a default function that takes in two values: req which stands for request, and res which stands for response. The response is returned as a JSON object with a key of name and a value of ‘John Doe’. Given that this information is stored in the “hello.js” file under the “api” folder, we can access the information we need from it externally. Let’s run npm run dev in our terminal and visit localhost:3000/api/hello. We can see below that the JSON object information is returned: 

You can also include additional configurations in Next.js when connecting to a database like SQL or an API like REST to fetch a wide variety of information from your database or API.

Dynamic Routes

Dynamic Routes are pages that allow you to add custom parameters to your URLs. It is like creating a folder in pages called “universities” and in that folder creating 2 files called “Canada.js” and “Germany.js”. Assuming we are running our application locally, when we navigate to localhost:3000/universities/Canada it will take us to the list of universities in Canada and if we go to localhost:3000/universities/Germany it will take us to the list of universities in Germany. With dynamic routing, we can replace both “Canada.js” and “Germany.js” with a single file in brackets called “[country].js”. The brackets tell Next.js that this file is dynamic and so now if we go to the same localhost:3000/universities/Canada or localhost:3000/universities/Germany it would still take us to the list of universities in Canada or Germany. The reason why this is so powerful is that if we have a database or an API with multiple countries, we don’t need to create a single file for each country page but instead create a dynamic page and have Next.js fill up the content of that page with its data i.e the universities in that country.

Data fetching

Next.js has 3 special methods that handle data fetching:

  1. getServerSideProps

  2. getStaticProps

  3. getStaticPaths

1. getServerSideProps

This is a server-side rendering (SSR) method that fetches data on every request. Server-side rendering as the name implies means rendering your components on the server before sending them to the browser. It is best to use this method only for pages whose data need to be fetched at request time. To use this method getServerSideProps, make a request to your database or API, and parse the data as a JSON object into props. In the example below, I have made a request to a public API that returns a list of universities in Canada. The first 3 universities are then stored in an array called “uniArray” and returned as props called “uni”.

export async function getServerSideProps() {

   const request = await fetch("http://universities.hipolabs.com/search?country=Canada");

    const data = await request.json()

    const uniArray = [data[0], data[1], data[2]]

    return {

        props : {uni: uniArray}

    }

}

2. getStaticProps

This is a static site generation (SSG) method that fetches data at build time. With this method, page load becomes very fast and gives a better user experience because the page doesn’t need to wait for an external response to display the data it needs. Data is fetched from your database or API only when you newly deploy your application to a server or if the server restarts. After fetching data it makes that data static so it doesn’t need to make another call each time a page is refreshed.

export async function getStaticProps() {

    const request = await fetch("http://universities.hipolabs.com/search?country=Canada");

    const data = await request.json()

    const uniArray = [data[0], data[1], data[2]]

    return {

        props : {uni: uniArray}

    }

}

We can also add the argument called unstable_revalidate in the return statement to send requests after some time has elapsed to fetch any new data from the database or API. In the example below, requests are made every 1 minute (60 seconds).

return {

        props : {uni: uniArray},

      unstable_revalidate : 60

    }

3. getStaticPaths

This is a static site generation (SSG) method that pre-renders a list of paths to different pages at build time. Inside each page, Next.js generates a route and HTML page. The data for each page is then fetched with the getStaticProps method. Take for example you want your website to contain the universities of different countries, with getStaticPaths you can fetch the details of those universities from a specific country you want by adding the name of the country at the end of the page URL like so: localhost:3000/universities/country/Canada. You should also make sure that the name of the file you are working with is a dynamic route by naming the file in pages/universities folder “[country].js”.

Now let’s see getStaticPaths in action, first, we have to fetch all the data of universities from every country, map through the data we just fetched, and return the data of universities for a single country as params. The params will be parsed through to paths. The specific country to look into will be determined from getStaticProps later on. After returning the paths for Next.js to navigate to, it is mandatory for us to also set a fallback key. fallback tells Next.js what to do when a path is not found. In this case, by setting fallback to false, we are telling Next.js to return a 404 page when a path(country) is not found.

export async function getStaticPaths() {

    const request = await fetch("http://universities.hipolabs.com/search?");

    const data = await request.json()

    return {

        paths : data.map( uni => {

            return {

                params: {country: uni.country}

//Make sure the key to uni.country is the same as filename. In this case since filename is [country].js the key to return is also country

            }

        }),

        fallback: false

    }

}

Now that we have the paths we must use getStaticProps to specify the country we want to look into. We do this by setting the params from getStaticPaths as an argument and using params.country in JavaScript’s fetch method:

export async function getStaticProps({ params }) {

    const request = await fetch(http://universities.hipolabs.com/search?country=${params.country});

    const data = await request.json()

    const uniArray = [data[0], data[1], data[2]]

    return {

        props : {uni: uniArray}

    }

}

You can see how it’s doing the same thing as before in the getStaticProps section:

const request = await fetch("http://universities.hipolabs.com/search?country=Canada");

But now instead of hardcoding the value in there, we are using getStaticPaths to tell getStaticProps what page to render.

const request = await fetch(http://universities.hipolabs.com/search?country=${params.country});

This is a powerful way of navigating through a website because it lets users decide on different page routes to visit and Next.js would render that page automatically.

Displaying the data

Displaying the data from getStaticProps or getServerSideProps is quite simple. Simply create a function component and parse in the name of the props from getStaticProps or getServerSideProps and map through the data you want the page to render. In this example, I parsed in the name of my props from earlier which was “uni ”:

return { props : {uni: uniArray} }

And created a function component called Universities where I rendered the country for the first university array and created a list where I mapped through all the university names and their domains in the country.

export default function Universities({ uni }) {

    return (

        <div>

            <h1>Universities in {uni[0].country}</h1>

            <ul>

                {uni.map((uni) => {

                    return (

                      <li>

                        {uni.name}. Website: {uni.domains}

                      </li>

                    )

                })}

            </ul>

        </div>

    )

}

Now, for example, if we want to see the page for the universities in Australia, all we have to do is run npm run dev in our terminal and then go to localhost:3000/universities/Australia:

And if we navigate to localhost:3000/universities/Japan:

Awesome! So with a single file within the pages folder called “[country].js” we can navigate through all the countries in our API, and Next.js would generate that page.

The Head component

This component enables you to provide additional information about the pages of your website in Next.js like meta tags, titles, descriptions, or keywords. To use it you first have to import the component from next/head:

import Head from "next/head";

export default function HomePage() {

  return(

    <>

      <Head>

        <title>My Next App</title>

        <meta name="description" content="An app built with Next/>

        <meta name="keywords" content="Nextjs, reactjs, production"

      </Head>

    </>

  )

}

Web crawlers also use this information in helping users see your website when contents in the metadata are searched.

Getting started with Next.js

Make sure you have node version 10.13 or later installed. To create a Next.js project, run the command npx create-next-app in your terminal. Your project will look like this after running the command:

Helpful scripts in Next.js

After creating a new project you are provided with some helpful scripts by Next.js which you can find in the “package.json” file and use in your terminal to begin development:

  1. next dev - Used to run the app in development mode. To use the command run npm run dev in your terminal.

  2. next build - Used to generate an optimized version of your app for production. To use the command run npm run build in your terminal.

  3. next start - Used to run the app in production mode. To use the command run npm run start in your terminal. 

  4. next lint - Used to find problems in your JavaScript code. To use the command run npm run lint in your terminal.

There is an additional command called next export which is not added by default to the “package.json” file but can be used by Next.js to export your application to static HTML. To use this command, first add “export”: “next export” in scripts like so:

"scripts": {

    "dev": "next dev",

    "build": "next build",

    "start": "next start",

    "lint": "next lint",

    "export": "next export"

  },

And run the command npm run export in your terminal.

Conclusion

Next.js is a great tool for developers to take large applications to production. It also has built-in CSS and Sass support. It’s a framework on top of a framework as some would say and so is not meant to necessarily replace traditional React applications but to improve performance in production.

4
$ 2.32
$ 2.32 from @TheRandomRewarder
Avatar for Sage_Osoro
1 year ago

Comments

Wow! this is a large article and excellent explanation of code next.js

$ 0.00
1 year ago