DEV Community

Cover image for Next.js: Understanding the Basics
Bu-jai
Bu-jai

Posted on

Next.js: Understanding the Basics

In this blog, we'll be discussing what Next.js is and begin to understand the very basics of Next.js. For this particular blog, we'll dive into Next.js 13 which is the newest version of the technology.


What is Next.js

Next.js is a React framework that helps ease the development process of building React web apps. Next.js helps developers by providing tools that help to solve most modern problems of building a web application. Some of these problems include routing, data fetching, performance, and the overall developer experience of building an app. Next.js is developed by Vercel and had its official release date in 2016. The latest version, Next.js 13, was released at the end of 2022. An important note to give is that the features of Next.js 13 can be incrementally adapted into older Next.js projects.


Routing (/app directory)

Before the advent of Next.js 13, developers used the pages directory for routing. However, with the release of Next.js 13, the Next team introduced the app directory. In Next.js 13, the app directory is the latest and preferred way to handle routing in a Next.js application. The new app directory uses file system routing to define the URL paths for an application. It is also built on top of React Server Components, which allows the app to render faster. Next.js 13 also introduces reserved file names:

  • page.jsx - The file that we will use most frequently. It contains the main UI of the route.
  • layout.jsx - The file that contains UI that is shared across multiple pages. If we don’t create one, it’ll be auto-generated.
  • loading.jsx - An optional file used to create a loading UI for a specific part of the app.
  • error.jsx - Similar to loading.jsx An optional file used to create an error UI for a specific part of the app.
  • There are more reserved file names, but these four are what I believe will be used most often.

** Note that the .jsx file extension is essentially the same as .js. The .jsx format is simply preferred for React apps.

Let's now take a look at what a URL path would look like using the new app directory. Any directories created in the app directory define the actual URL structure of the app. So a directory structure that looks like this.

Route example

Would have the URL structure of www/websitename/settings

Dynamic Routes

With more complex web apps developers can not always know the paths ahead of time. For this, dynamic routes are the answer. A common example of dynamic routes being used is blogs. A blog website always looks the same, except for the main contents of the blog. To define a dynamic route in Next.js, we enclose a directory with brackets. Take a look at the directory structure below.

Dynamic routes example

For a blogging website with thousands, maybe even millions of users. Accessing a particular blog is handled by the id of that blog. Here’s an example

User’s Blog URL
Kevin’s blog www/blogwebsite/blog/7E4DxTnveS
Bob’s blog www/blogwebsite/blog/QJ0ojiIfvS

The ending URL segment corresponds to the blog id of that user’s particular blog.

Route Groups

Route Groups are another feature of Next.js 13 that allows us to break the app directory mapping the folders into the URL paths. A reason why we might want to do this is to organize our routes without affecting the structure of the URL in our app. To define a Route Group simply enclose a directory with parentheses.

Here’s a picture from the Next.js 13 docs that might help visualize what I mean.

Next.js 13 route groups


Server/Client Components

All components created under the app directory are automatically inferred as React Server Components. The main reason for this change is because Server Components helps developers more easily render components on the server, and it also reduces the amount of JavaScript shipped to the browser. Which leads to better performance. In Next.js 13, when a page is loaded, the initial HTML is first rendered in the server. The HTML is then progressively enhanced in the browser.

A component can be turned into a Client Component by adding 'use client' at the start of the file. Here’s an example:

'use client';

// Your React code here...
Enter fullscreen mode Exit fullscreen mode

The Next.js 13 docs provide a list on when to make a component a Server or Client Component. Here are some of the examples:

Use Case Server Component Client Component
Fetch data ⚠️
Access the back end (directly)
Add interactive elements and event listeners
Use State and Lifecycle Effects

Data Fetching

With Next.js 13, the Next.js team introduced a new way to fetch data. Their main goal was to streamline the API to make sure it aligns with React and the Web platform. Next.js 13 now uses the fetch() native Web API, and makes use of async/await in Server Components. When fetching data, the Next.js team recommends always fetching data in Server Components. The reason being:

  • Allows the page to have direct access to the back end
  • Keep the application secure by not allowing the client to see sensitive information
  • Fetch data and render in the same environment

Here’s what fetching data in a Next.js 13 app would look like.

async function getUserData() {
    // Fetching data in Next 13 using the native fetch() function
    const res = await fetch('https://api.com/...');

    // Return the data as JSON
    return res.json();
}

export default async function User() {
    const userData = await getUserData();

    // Rest of your React code here...
}
Enter fullscreen mode Exit fullscreen mode

** An important note to add is that previous Next.js data fetching methods (getServerSideProps, getStaticProps, and getInitialProps) are not supported in the new app directory.


Hello World!!

Now that we have a rough idea of how a Next.js 13 application functions. Let's create a simple “Hello World” web app.

The first step is to check if you have Node.js 16.8 or higher as Next.js 13 requires it. If you're not sure if you have a compatible version of node, simply use this command: node -v. If your version is out of date or if you don’t have Node installed in your system, download Node.js here.

Now that we have the right version of Node, we can start building our Next.js 13 app.

  • Run npx create-next-app@latest hellonext13. This creates a Next.js 13 app with the name hellonext13.
  • Now, delete the pages directory since that’s the old way of doing it. Create a new folder called app. Under app create a file called page.jsx. Inside the page.jsx file, add the following lines of code:
import React from "react";

export default function Page() {
    return (
        <div>
            <h1>Hello World!</h1>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode
  • Since the app directory is experimental as of right now, we’ll have to add something in the next.config.js file. In the file, add the experimental flag to enable the app directory.
/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
    /* --> add this code <-- */
    experimental: {
        appDir: true,
    },
};

module.exports = nextConfig;
Enter fullscreen mode Exit fullscreen mode
  • Once we’ve changed and saved next.config.js. We’re ready to run the application. In the command line, type the following command: npm run dev. This will launch the application.
  • Go to http://localhost:3000/ and you should see your application.

Hello World app


Thanks for taking the time to read my blog. Hopefully, you have learned something about Next.js 13. For more information about Next.js, I highly recommend watching a video, reading other blogs, and reading the Next.js docs.

Top comments (0)