How to Build Web Apps With Next.js: A Step-By-Step Next.js Tutorial

6 min read

  • Languages, frameworks, tools, and trends
Next.js Tutorial on How to Build Web Apps

Next.js is a full-stack web framework built on top of React and extends it with features like static site generation, and server-side rendering. It is termed a full-stack framework because it has a built-in and out-of-the-box backend server that enables developers to create an API for the project.

This article will take you through the features of Next.js assuming that you have the basic understanding of React and JavaScript.

Initializing a Next.js project

A Next.js project can be initialized using a Command Line Interface (CLI) known as create-next-app that bootstraps a Next.js project within a directory of your choice.

To get started run the command below:

bash
	npx create-next-app
Bash

You’ll be asked some questions on the project configuration as below, but in this article, we’ll use JavaScript for the project.

Initializing Next.js project.webp

Note: The experimental app directory presenting a new feature in Next.js 13 that was released on October 2022 and we’ll get to it later.

Project folder structure

After the project is initialized you’ll see a folder structure below:

|----app
|----node_modules
|----public
|----.gitignore
|----jsconfig.json
|----next.config.js
|----package.json
|----postcss.config.js
|----README.md
|----tailwind.config.js
JavaScript

Now let’s go through each folder and see its uses.

app directory

This is the new folder introduced in Next.js 13 that simplifies routing in Next.js applications as it uses file-based routing which means pages are created based on files and folders created in the app directory. We’ll see the app directory in action later in the article.

node_modules

This contains all the Node.js downloaded dependencies that will be used within the project, by default it is not tracked by git.

public folder

This folder contains assets like images, favicons, and sitemaps that can be used within your project for users to see publicly across the internet.

pages folder

This was and is still used in Next.js to enable routing in Next.js applications but it is not advanced like the app directory in layouts and handling metadata.

Note: You may not see this directory if you selected the experimental app directory option during project initialization.

next.config.js

This file is used to store projectwise Next.js configurations like external images, opting for the experimental app directory, and other configurations.

package.json

This file is used to store the list of packages or dependencies used within the Next.js project.

The app directory

In the previous versions of Next.js, routing was based on file system routing and was all done in the pages directory, but from Next 13, the app directory was introduced and it came with a lot of features like React server components, File based routing like in pages directory but with a different structure, Next js actions, Layout groups.

Let's see the app directory in action.

Defining routes

If you've initialized the Next project for the first time and opened the app directory, you'll see a folder structure like below:

|--app
|----layout.js
|----page.js
|----api/
|----favicon.ico
|----globals.css
Plaintext

page.js file defines the route or path in a webpage and takes the name of the folder within it, if it is in the root (app) directory it will map to the homepage of the website i.e / the route of the website.

layout.js file defines the layout that encapsulates a particular route if placed in a folder. However, when placed in the root (app) directory it defines the layout for the whole web application, so all the descendant routes will have the layout defined in the file.

For creating specific routes for example /blog, you’ll have to create a folder named blog within the app directory and create a page.js file within the folder that exports a function component as below:

js
export default function Page() {
	return (
<div>
  <h1>Blog Page</h1>
</div>
);
}
JavaScript

Run the server and navigate to /blog and you’ll see a page with the heading Blog Page, that’s it you’ve defined a route in Next.js, but by default, all components and routes in the app directory are server components which means they do not support client-side interactions like forms so if you want to use make client-side components you use a directive

js
“use client”;
JavaScript

on the first line of the page.js that you want to make as a client component.

Dynamic routes

We have seen how to define static routes, but if we want to define dynamic routes like /blog/<slug> where slug changes for each blog page, we need to enclose the dynamic route folder with square brackets like,

|--blog
|----[slug]
|-------page.js
JavaScript

And to access the value of slug from the path, we use the params prop passed to the function component handling the route as shown below by accessing the route name in our case it is slug by destructuring the params object.

jsx
export default function Page ({ params }) {
	const { slug } = params;

	// rest of the code continues
} 
JavaScript

In the previous versions of Next.js, navigation was done through the Link component imported from next/link, i.e

js
import Link from “next/link”;
JavaScript

This requires an href attribute for the destination path and was necessary to be enclosing an ‘a’ tag with no href attribute, for example

jsx
	<Link to=”/blog”>
		<a>Blog</a>
	</Link>
JavaScript

But as of Next.js 13, the Link component is also used for navigation but it is not necessary to be enclosing a tag, you can use it on any React component or HTML element like

jsx
	<Link href=”/blog”>
		<p>Blog</p>
	</Link>
JavaScript

Dynamic page navigation

Sometimes you will want to redirect a user to a specific page after completion of a particular task, like filling in a subscription form, so you can use a hook from Next.js known as useRouter, that will enable the dynamicity of page navigation in Next.js 13 apps. Let’s see it in action by assuming a payment subscription process in our app.

jsx
import { useRouter } from “next/navigation”;

export default function Page(){
	const router = useRouter();

	const handleSubscription = (e) => router.push(“/home”);
	
	return (
		<button onClick={handleSubscription}>Pay now</button>
);
}
JavaScript

The above code pushes the /home route after the payment process using the push method from the useRouter hook, Also the hook contains other methods like .refresh() that refresh the page after a certain action is complete.

Defining route layouts and layout groups

Defining layouts in Next.js in the app directory uses the layout.js but layouts can be limited to specific pages or defined globally, when a layout.js file is created in the root app directory, it applies to all pages of the website but when created in a specific route folder, it only applies to that specific route.

But sometimes you might want to group specific routes with the same layout that doesn’t share with other pages, there you will have to use Layout groups. These groups are defined by putting all common pages sharing the same layout in a folder whose name is enclosed with round brackets as shown below.

|--app
|----(auth)
|------layout.js
|------login
|--------page.js
|--------loading.js
|------signup
|----(main)
|------layout.js
|------dashboard
|--------page.js
|--------loading.js
JavaScript

The layout.js file defined in route groups will only apply to the routes within that specific folder but if there is a layout file defined globally, it will also inherit that layout too.

Special files in the app directory

Until now we've only interacted with two special files introduced in Next.js 13, which are page.js and layout.js, but there are other types of files that perform specific functions for example.

  • loading.js - this special file is placed in a specific page directory in the app that will render when the required page is being built and fetched from the server.
  • error.js - this file is used to show a friendly error page when an error occurs and you can embed a refreshing functionality in it to reset the application
  • head.js - this is used to set specific <head> tag for a particular route, and can be used in dynamic routes too.
  • template.js - this is similar to the layout.js file but it will remount on navigation and the state is not shared.

As of now, we can see the powers of Next.js in building scalable web applications, therefore, after getting comfortable with the basics take practice a lot by building projects and exploring the Next.js documentation for more about the React framework.

Conclusion

With this article, you can easily be getting started with Next.js and explore the basic yet essential features required to become a Next.js developer. This documentation will also help you to start building a Next.js project using JavaScript. We hope after this you continue to keep exploring the awesome features of Next.js and build advanced level projects with it.

How to Use Webpack With React

Author
Shabani Nassibu

Shanas is a software developer with 3 years of experience and a technical writer specialized in frontend development with tech stacks like Nextjs, React, Vue, Tailwind and backend development with Django, django rest framework. He is currently working as a freelancer but he is open to any remote job opportunities.

Share this post