DEV Community

Cover image for Next.js Tutorial with Examples: build better React apps with Next
Ryan Thelin for Educative

Posted on • Originally published at educative.io

Next.js Tutorial with Examples: build better React apps with Next

Next.js is a React front-end framework that lets you optimize performance and user experience through additional pre-rendering features like out-of-the-box server-side rendering and static generation. Next.js is used by full-stack developers to build reactive websites as it requires a good understanding of both client-side React and server-side architectures.

Today, we'll help you get started with Next.js by covering the main concepts you need to know before you start building optimized sites.

Here’s what we’ll cover today:

Optimize your webpages with Next.js

Learn Next.js with hands-on examples and build a resume-building Giphy search page at the same time.

Next.js - The ultimate way to build React apps

What is Next.js?

Next.js is an open-source React front-end framework that adds additional optimization capabilities like server-side rendering (SSR) and static-site generation. Next.js builds on the React library, meaning Next.js applications take the benefits of React and just adds additional features.

Server Side Rendering. SSR allows the server to access all required data and process the JavaScript together to render the page. Then, the page is sent back in its entirety to the browser and immediately rendered. SSR allows webpages to load in a fraction of the time and increases user experience with added responsiveness.

Search Engine Optimization (SEO). Using SSR also gives you an edge on SEO, which helps your site show up higher on search engine results pages. SSR makes websites rank better for SEO because they load faster and more of the site content can be scanned by SEO trackers.

<head> tag. Next.js also allows you to edit the <head> tag of a site, which you cannot do in React. The <head> tag is a core part of a webpage's metadata and contributes to the site's SEO ranking.

Overall, Next.js is considered to be a more fully-featured version of React that maintains the intuitiveness React Framework is known for.

Why use Next.js?

The main advantage of Next.js is the built-in SSR support for increased performance and SEO.
Server-side rendering works by altering the request flow of the React application such that all components except the client send their info to the server.

With all info on the server, it can pre-render the HTML of the page. The client can send a single request to the server and receive the full HTML page rather than requesting each component individually with client-side rendering.

Alt Text

Pros:

  • Next.js apps load considerably faster than React apps due to out-of-the-box server-side rendering.
  • Supports static-site export features.
  • Quick to learn for anyone with previous React experience.
  • Automatic code splitting for pages.
  • Easily to build internal APIs through built-in API routes and create API endpoints.
  • Built-in support for page routing, CSS, JSX, and TypeScript.
  • Quick to add plugins to customize Next.js to your specific page's needs.
  • Maintains the benefits of React such as intuitive component-driven creation, front-end state system, and high popularity.

Con:

The only real downside of Next.js is that it's an opinionated framework, meaning it has a specific method and toolset that it wants you to use to construct your apps.

However, the preferences of Next.js will fit well within the scope of most projects.

Fun Fact: Educative recently switched to Next.js on top of React. If you’ve used Educative in the last few months, you’ve already enjoyed some benefits of Next.js!

When to use Next.js

Next.js is best suited for making an optimized landing or homepage as well as any other pages that rely on organic search traffic. These pages will see the most benefit from SEO improvements of Next.js.

Next.js is also better for websites than web apps as SSR allows it to have the same performance regardless of the device the client is using.

Next.js is less ideal for creating web applications or secured applications that require authentication because these do not benefit server-side rendering.

Next.js Example

Let's see an example of a full Next.js application so you can see how it's laid out.
We'll use the default Next.js app generated with a new project.

Alt Text

The index.js file which represents the single page on this project looks like this:

import Head from 'next/head'
import styles from '../styles/Home.module.css'
export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
        <p className={styles.description}>
          Get started by editing{' '}
          <code className={styles.code}>pages/index.js</code>
        </p>
        <div className={styles.grid}>
          <a href="https://nextjs.org/docs" className={styles.card}>
            <h3>Documentation &rarr;</h3>
            <p>Find in-depth information about Next.js features and API.</p>
          </a>
          <a href="https://nextjs.org/learn" className={styles.card}>
            <h3>Learn &rarr;</h3>
            <p>Learn about Next.js in an interactive course with quizzes!</p>
          </a>
          <a
            href="https://github.com/vercel/next.js/tree/master/examples"
            className={styles.card}
          >
            <h3>Examples &rarr;</h3>
            <p>Discover and deploy boilerplate example Next.js projects.</p>
          </a>
          <a
            href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
            className={styles.card}
          >
            <h3>Deploy &rarr;</h3>
            <p>
              Instantly deploy your Next.js site to a public URL with Vercel.
            </p>
          </a>
        </div>
      </main>
      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
        </a>
      </footer>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

The index file is the core of this application as it only contains this single page. Real websites will contain multiple pages under the pages folder which each represent a different webpage.

Keep learning Next.js.

Next.js is the future of React development. Start building web pages that work for your users, not against them.

Educative's hands-on courses let you learn cutting-edge technologies in half the time, without the complicated set-up. By the end, you'll have a finished Giphy search project and Next.js certification to stand out to recruiters or current employers.

Next.js - The ultimate way to build React apps

Get started with Next.js

Now let's get you started with some hands-on Next.js code. We'll cover the 5 essential concepts visible in the default application that you'll need to create your own Next.js project.

Requirements and Environment

Before we get started, let's set up everything you need. You'll need Node.js, npm, and npx before you download Next.js.

You can install Node.js on their official site. To confirm it's downloaded correctly, enter node -v into your command prompt. Usually, npm and npx will come as part of your Node.js installation.

To confirm that these have been installed correctly, enter npm -v and npx -v into your command prompt. Each will return their version respectively.

If all three of these tools are installed correctly, you can install Next.js with Node.
Enter npm install next react react-dom into your command prompt.

Once it has successfully installed you'll receive the following message with your current Next and React versions:

+ react@16.13.1
+ react-dom@16.13.1
+ next@9.4.4
added 831 packages from 323 contributors and audited 834 packages in 172.989s
Enter fullscreen mode Exit fullscreen mode

Create Next.js App

You can create a fresh Next.js application using the create-next-app command or manually.
Using create-next-app is easier as all you need to do is enter npm create-next-app <app-name> into your command prompt.

Alternatively, you can open your package.json file and enter the following scripts:

"scripts": {
  "dev": "next dev",
  "start": "next start",
  "build": "next build"
}
Enter fullscreen mode Exit fullscreen mode

This allows you to start your new application in different modes:

  • dev starts Next.js in development mode.
  • start starts Next.js in production mode.
  • build builds your Next.js app for production. Regardless of which method you choose, this will generate the basic Next.js application template we saw earlier.

If you run this app using next dev, you'll see the default Next.js page on http://localhost:3000.

Alt Text

Next.js Folder Structures

Next.js uses a minimalist file-system to avoid a cluttered project file, meaning the starting point contains only the bare minimum required to run the app. Understanding this folder structure will help you manipulate it to fit your own projects.

Each Next.js project starts with 3 folders: pages, public, and styles.

Here's an example of what you'll find in a fresh Next.js project:

 // other files and folders, .gitignore, package.json, next.config.js...
- pages
  - api
    - hello.js
  - _app.js
  - index.js
- public
  - favicon.ico
  - vercel.svg
- styles
  - globals.css
  - Home.module.css
Enter fullscreen mode Exit fullscreen mode

Pages

The pages folder contains your page files. Each page file is a React component with a unique route automatically created from the file name. For example, the Next.js page hello.js would be found at pages/hello.js.

Some pages, like _app.js above, include an underscore prefix in their name to mark them as custom components. These components are used by Next.js to work with other components.

For example, _app.js is used to start each page and is not used as its own webpage.

Public

This folder is for static file serving, meaning these files do not change and can only be referenced. This folder often contains images or icons the site uses as well as internal information like Google Site Verifications.

In our public folder, we have favicon.ico which is a small icon to use on browser tabs, and vercel.svg which displays the platform company's icon.

Vercel and Netlify are the most popular hosting and serverless services for Next.js

Styles

This folder contains our CSS style sheets, which determine the appearance of all of our page elements. The globals.css file sets the general standard that all pages in the project will use.

You can also add component-specific styling using module files named with a module suffix, <componentName>.module.css.

Routing/Navigation in your App

Navigation refers to the ways your users can navigate through your Next.js website. Routes and Links are the two main methods you can use to define site navigation.

Routes in Next.js are approachable due to the built-in route definitions of each component. To optimize your app routing, it's important to understand the index, nested, and dynamic routes.

Index

Index files like index.js are routed to the starting point of your application /, rather than /index. You can use this to your advantage by creating multiple index files that act as the landing page or start point of different navigation paths within your site.

- pages
  - index.js # found at `/`
  - users
    - index.js # found at `/users`
    - account.js # `/users/account`
Enter fullscreen mode Exit fullscreen mode

For example, the index.js page under just pages is the homepage of the site that is reached if no additional route is entered. The second index.js under users is the landing page for the users path, reached by entering <siteName>/users.

Nested

Nested routes are routes that are only accessible through a shared parent route, such as /users/account. You can think of nested routes like nested files on your computer in that you have to navigate through all higher components to reach the nested component.

Dynamic Routes

We can also include parameters in our routes to allow for variable behavior. Dynamic pages are defined with square brackets. This feature essentially allows us to pass information to a page like we would a function.

For example, we could remake our user component to allow each user to have their own accounts page.

# ...
  - users
    - index.js
    - [account.js] # `/users/[accountName]`
Enter fullscreen mode Exit fullscreen mode

With this setup, users can enter their account name in the URL and immediately go to their account information page rather than starting at users. In other words, I could enter my account name, /users/educative, to reach a dynamic page that populates with the information relative to the account name entered.

The account.js file will need to include conditional statements that tell it what to do based on what parameter it is passed.

   if(id == 'one'){
      return postOne;
   }else if(id == 'two'){
      return postTwo;
   }  
Enter fullscreen mode Exit fullscreen mode

Linking

You can also introduce client-side click-through links to allow users to navigate the site without the URL bar. The Link React component is the key to linking in Next.js.

The Link component takes an href argument populated with the file route of the destination component. This will create a link between the current page and the page found at the entered route. For example, if you add <Link href= "/users/"> to hello.js, you will create a link from hello.js to the users landing page.

import Link from 'next/link'
import Head from 'next/head'
function HomePage(props) {
   return (
      <>
         <Head>
            <title>Welcome to Next.js!</title>
         </Head>
         <div>Welcome to Next.js!</div>
         <Link href="/users">> <a>Users</a></Link>
         <br/>
         <img src="/logo.png" alt="EducativeLogo" />
      </>        
   )
}
export async function getServerSideProps(context) {
   const res = await fetch('https://api.github.com/repos/vercel/next.js')
   const json = await res.json()
   return {
      props: { stars: json.stargazers_count }
   }
}
export default HomePage
Enter fullscreen mode Exit fullscreen mode

Next.js Data Fetching

Data fetching is when Next.js requests data from a server to generate a page. Choosing the right pre-render methods and fetch functions is essential to making user-friendly apps

The page can be generated with either SSR, which has the server render the full page upon receiving the request, or static generation, which caches a previous render of the page so it can be delivered immediately.

  • SSR: Better for highly interactive or rapidly changing pages that don't work with static generation.
  • SG: Better for text-only pages or pages that do not change because the static render will always meet the needs of the user.

You can use one or the other fetching method, or you can implement a hybrid system.
Next.js has 3 async data fetching functions that act as centralized fetching alternatives to the traditional React method. These functions are:

getStaticProps: used with SG to pull page content from external data.

export async function getStaticProps() {
  // This is a real endpoint
  const res = await fetch('https://sampleapis.com/fakebank/api/Accounts');
  const accounts = await res.json();
  return {
    props: {
      accounts: accounts.slice(0, 10),
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

getStaticPaths: used with SG to pull page paths from external data.

export async function getStaticPaths() {
  // Fetch the list of states
  const res = await fetch("https://sampleapis.com/the-states/api/the-states");
  const states = await res.json();
  // Create a path from their ids: `/states/1`, `/states/2` ...
  const paths = states.map((state) => `/states/${state.id}`);
  // Return paths, fallback is necessary, false means unrecognized paths will
  // render a 404 page
  return { paths, fallback: false };
}
Enter fullscreen mode Exit fullscreen mode

getServerSideProps - used with SSR to pull pre-rendered pages at build time.

export async function getServerSideProps(context) {
   const res = await fetch('https://api.github.com/repos/vercel/next.js')
   const json = await res.json()
   return {
      props: { stars: json.stargazers_count }
   }
}
export default HomePage
Enter fullscreen mode Exit fullscreen mode

Projects to build with Next.js

Now that you've tackled the basics of Next.js, it's time to jump into your own projects. Here are some beginner project ideas to get you started:

  • To practice working with external data: Giphy search app that pulls results from an external database

  • To practice static generation: National info site that displays the flag, population, and geographic size of every country

  • To practice navigation: Instagram-like social media webpage that displays a user's pictures on the account page and likes/comments on each individual picture

To help you get the most out of your project, Educative has created Next.js - The ultimate way to build React apps. This course walks you through the basics of Next.js as you build each component of the Giphy search project. By the end of the course, you'll have a fully optimized and deployed Giphy search page that you can put on your resume or LinkedIn.

Happy learning!

Continue reading about React

Top comments (1)

Collapse
 
lyrod profile image
Lyrod

Dynamic routing: [account.js] -> [account].js
Typo in link example: ">"

SSR is not for page at build time but at every request