- Published on
Creating Website With Next.Js: A Beginner Guide
Creating website with Next.js is becoming increasingly popular nowadays, especially among developers who are familiar with working in React and JavaScript environments.
Next.js is one of the React frameworks, similar to Remix and Gatsby. These frameworks are designed to provide ease and efficiency in developing optimized websites. They have inspired many web developers to enhance the user experience in ways that have never been seen before.
This article assumes that you have some understanding of React, typescript and javascript. However, if you don’t, it’s OK. Just ignore them for now! And you can skip directly to the section on “installing Next.js.”
The key points you need to grasp from this article are: 1) Installing Next.js, 2) Routing concepts, 3) Rendering concepts, and 4) Deploying your Next.js web to the internet.
An Overview of React
Before we dive into learning how to create websites with Next.js, let’s briefly talk about React. React is a JavaScript library released by Facebook, now Meta, in 2013. In recent years, React has gained popularity and even surpassed Angular, a JavaScript framework developed by Google, which had been around for longer.
One of the advantages of React is its ease of building web applications using a component-based approach. With React, developers can create complex applications without struggling to organize and maintain their code. Adding features and debugging also become easier than ever before.
Why Next.js?
Creating a website with Next.js is a better choice compared to building directly with React. This is due to a notable limitation of React, which is its suboptimal support for SEO (Search Engine Optimization).
This limitation arises because React was originally designed to work on the client-side (browser) in what is known as Client-Side Rendering (CSR). In CSR, the website’s content is generated by JavaScript on the client-side after the page loads, which is not ideal for SEO purposes.
To overcome this limitation, in 2016, a React framework called Next.js was introduced to complement React’s shortcomings, not only in terms of SEO optimization but also by providing other useful features in web development that may not be available in React or are still in development.
Advantages of Next.js
Next.js offers several advantages in website development. In at least version 13, some of these advantages include:
- File-based routing. With this feature, you can create website navigation simply by creating a “page.js” file in your program folder, without the need to install any additional modules.
- Built-in web optimization. Next.js automatically optimizes images, fonts, and scripts without requiring any manual configuration or additional module installation.
- Easy server-side or client-side rendering configuration. This feature allows developers to choose which pages to optimize for SEO and which ones to render on the client-side.
- Next.js is powered by Turbopack and SWC, enabling faster development.
Regardless of the numerous advantages that Next.js offers compared to React, Next.js is not a competitor or alternative to React like Vue.js or Nuxt.js. Next.js is a React framework dedicated to website development. This means that if you understand and can work with React, you can apply all of that knowledge and skill to Next.js.
Installing Next.js
Before starting the Next.js installation, make sure you have Node.js installed on your computer. Next.js requires Node.js to run its development environment. Additionally, ensure you install npm. For the editor, you can use Visual Studio Code.
Once everything is ready, open the terminal or command prompt and create a new directory to store your Next.js project. To open the command prompt in Windows, you can type ‘command prompt’ in the Windows search menu.
Navigate to the project directory using the command ‘cd directory_name’.
Alternatively, you can open the file explorer and select the folder you want to use as the project folder. Then, within that folder, press Shift+Right-click to display the command prompt.
In the selected project folder, enter the following command in the command prompt.
npx create-next-app@latest
You will see then the following questions displayed, which you need to answer.
What is your project named? my-app
Would you like to use TypeScript with this project? No / Yes
Would you like to use ESLint with this project? No / Yes
Would you like to use Tailwind CSS with this project? No / Yes
Would you like to use `src/` directory with this project? No / Yes
Use App Router (recommended)? No / Yes
Would you like to customize the default import alias? No / Yes
The first line is for your project’s name. You can name it freely, for example, “my-app,” “cool-web,” or any other name you prefer. For the remaining questions, if you are not fully sure, simply answer “yes” to each question. Then, wait until the installation process is complete.
Once all the installation processes are finished, you can check your project folder. The folder, which was previously empty, now contains a file structure like the image below.
picture
With Visual Studio Code, open the package.json file. You will see the code block like below.
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
}
Pay attention to the script block in the file. The codes for dev, build, start, and lint are commands that you can later input into the terminal or command prompt.
Running Next.js
To run the program, let’s try entering the command ‘dev’. Type ‘npm run dev’ into your command prompt and press enter.
image
If the process is successful, you will see the message “the web is ….” on the console screen. This means that you can access your web in the browser at ‘localhost:3000’. Now, open your browser and enter that address!
image
Congratulations! You have successfully created a website with Next.js.
Next, open the file ‘page.tsx’ in the editor. Modify the <title> tag with your name or any desired title, then save (ctrl+s). Automatically, you will see the changes reflected in ‘localhost:3000’ on the browser. This is the purpose of the ‘run dev’ command, to run the program in development mode.
Stop the program by pressing ‘ctrl+c’ in the console. Once it stops, let’s switch to the command ‘npm run build’ and press enter. On the console screen, you will see the building process, where Next.js components turn into JavaScript and CSS files stored in the ‘.next’ folder.
image
After the building process is complete, you can run the command ‘npm run start’. We use this command to run the program stored in the ‘.next’ folder.
Now, you can open the browser again and go to ‘localhost:3000’. You will see the same page as before. However, this time, the loading time is faster.
If you make edits to the ‘page.ts’ file, the changes will not appear in the browser. This is because the program running in the browser is the production mode program derived from the ‘.next’ folder, which is no longer editable. If you want to make changes, you will need to repeat the ‘npm run build’ command as before.
Exploring Core Features
Creating a website with Next.js offers many conveniences. However, for now, let’s focus on discussing the routing feature.
1) Routing
One of the typical features of Next.js is its routing capability. To understand it, create a new folder named “about” inside the /app folder. image
Inside the “about” folder, add a file named “page.tsx”. Open the file and insert the following code, then save it.
// about/page.js
export default function Hello() {
return (
<div>
Hello, I'm a creator of this website
</div>
)
}
Run the command ‘npm run dev’ as before. Open your browser and go to the address ‘localhost:3000/about’. The browser will display the following:
image
Similarly, if you want to create a webpage, for example, “address” (or any other name), create a folder named “address” inside the /app folder. Inside the “address” folder, create a file named “page.tsx” just like before. Insert the following code. Remember, the file name must be page.tsx, it cannot have a different name.
//address/page.tsx
export default function Address() {
return (
<div>
Hello, it is address page
</div>
)
}
Next, navigate to the address ‘localhost:3000/address’ in your browser, and it will display as shown in the image:
image
This is called static routing in Next.js, which is navigating website pages by creating page.tsx files.
Such routing can be further developed into nested routing.
What is nested routing?
To understand it, let’s use the project we previously created. Inside the “about” folder, create another folder, for example, “me”. Inside the “me” folder, create a file named “page.tsx” as before. The file structure will now look like this:
image
In the newly created page.tsx file, insert the following code:
// about/me/page.tsx
export default function Me() {
return (
<div>
Hello, it is me
</div>
)
}
Run the program with ‘npm run dev’ as usual. Then, open your browser and go to the page ‘localhost:3000/about/me’, and it will display as follows:
image
Feel free to further develop the /about or /address pages as shown in the example above. This routing feature allows us to easily create website pages by simply creating folders and page.tsx files.
Static And Dynamic
Static routing is rendered statically by Next.js. This means that the HTML structure of the page is stored in cache, resulting in faster subsequent requests for the same route.
In addition to static routing, there is also dynamic routing, where the page.tsx component can dynamically receive parameters. We will discuss this in another opportunity.
2) File Conventions
Routing in Next.js is based on the file system. For example, the page.tsx file must always exist to display web content in the browser. If there is no page.tsx file, nothing will be displayed in the browser.
In addition to page.tsx, Next.js has other standard file names that are fixed and should not be changed. These files are layout.tsx, error.tsx, not-found.tsx, and loading.tsx. These file names must not be freely changed. If they are renamed to something else, the files will not function as intended.
In the root folder of your project, make sure you have the following file structure. If not, create the files accordingly. You can also apply this file structure to other folders, such as the about folder, about/me folder, or the address folder we created earlier.
image
These files have automatic functionality. I will discuss layout.tsx, not-found.tsx, and error.tsx. We will cover loading.tsx in another opportunity.
layout.tsx
Open the layout.tsx file. If it is still empty, fill it with the following code:
//layout.js
export default function Layout({children}) {
return (
<div color='red'>
{children}
</div>
)
This code contains a Layout component that will make any content inside it appear in red color.
Run the program with npm run dev, then check in the browser. The text that was previously not colored will now appear in red. This is because the Page component automatically becomes the children of the Layout component. In other words, the Layout component automatically wraps around the Page component.
not-found.tsx
Open the not-found.tsx file. If it is still empty, fill it with the following code:
// not-found.js
export default function NotFound() {
return (
<div>
<h1>Page not found</h1>
</div>
);
}
Run the program with npm run dev. In the browser, enter the address localhost:3000/about/you.
image
The browser will display the text “Page not found” as shown above. This text comes from the NotFound component. This component is automatically called because the requested route doesn’t exist since we didn’t create the /about/you route previously.
error.tsx
Open the error.tsx file. If it is still empty, put the following code:
// error.tsx
'use client'; // Error components must be Client Components
import { useEffect } from 'react';
export default function Error({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error);
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
);
}
Just like the NotFound component, the Error component above can also be called automatically. The difference is that the Error component is called when there is a problem with the program, either due to program bugs or failures in retrieving data from the database.
3) Components within Components
In the discussion above, we have learned how the Page component is automatically wrapped by the Layout component. However, we can also freely create other components and manually wrap the Page component. How can we do that?
Create a file named home-layout.tsx in the /app folder. You can choose any file name. Then, enter the following code:
// /home-layout.tsx
"use client"
export default function HomeLayout({children}) {
console.log("I'm in browser")
return (
<div>
<h1>
{children}
</h1>
</div>
)
Then, open the page.js file in the /app folder and modify the code as follows:
// page.js
import HomeLayout from "./home-layout";
export default function Home() {
console.log("I'm in server")
return (
<HomeLayout>
Hi, I'm page component from root and
I'm wrapped by home-layout component
</HomeLayout>
)
Take note of the import statement for HomeLayout. The text displayed by the page.tsx component is wrapped by the HomeLayout component, which is imported from home-layout.tsx.
Run the program using npm run dev. Then, go to the localhost:3000 page in your browser. It will appear as follows:
[image]
In the browser, the displayed text is “Hi, I’m the page component … so on”. This text originates from the page.tsx component. It is displayed in bold because it is wrapped by the HomeLayout component imported from the home-layout.tsx file, which includes an <h1> tag. Additionally, the text is displayed in red because both the Page and HomeLayout components are automatically wrapped by the Layout component.
4) Rendering
In the code of home-layout.js, take note of the line “use client” and the console.log(“I’m in the browser”). By using “use client,” we will render this component in the browser and display the text “I’m in the browser” in the browser’s console.
On the other hand, in page.tsx, we don’t use “use client” because we will render the page.tsx component on the server (server rendering). Therefore, the phrase “I’m in the server” will be logged on the server and not in the browser.
Next, open the browser console by pressing Ctrl+Shift+I. In the browser’s console, you will see the text “I’m in the browser” displayed. This indicates that the home-layout.tsx component is rendered on the client-side (client rendering).
Now, take a look at the server console or the command prompt where you ran the npm run command. You will see the text “I’m in the server” displayed there. This indicates that the page.tsx component is rendered on the server-side (server rendering).
Deploy to The Internet
Now, for the final lesson, let’s deploy to the internet!
By releasing your web application to the internet, it can be accessed by anyone connected to the internet. To do this, we need a host provider for the web we’ve created.
Fortunately, there are many providers that offer free features for node.js-based applications, such as glitch.com, vercel.com, and netlify.com. Here, we will use vercel.com.
Before we begin, make sure you have a GitHub account. If you do, push the program code we created earlier to a GitHub repository. Here’s how you can do it:
In Visual Code, sign in to your GitHub account by clicking the account button in the bottom left corner. Once connected to GitHub, navigate to the branch button just below it. Click on it, and the option to create a branch will appear.
Image
Click “create branch” as shown in the image above. Then, give a name to the branch you will create on GitHub, for example, “myweb”. Wait for the upload process to complete. Once done, go to your GitHub account. Make sure there is a repository with the name you created earlier, “myweb”. Open that repository and note that the files in it are the files from your project.
After creating the repository, it’s time to create an account on vercel.com. Sign in with your GitHub account and follow the steps. Once your account is verified, go to the dashboard page.
Image
In the dashboard, connect your account to the “myweb” repository you created on GitHub. If the integration is successful, it will look like the image below.
Image
Click on the URL address provided in the dashboard! That is the internet address for your new website. Congratulations!
Image
Conclusion
Both React, Next.js, and other frameworks are front-end development tools for web applications. In this article, we haven’t discussed how to consume data from the back-end (database server or API server).
In future articles, we will learn how to create websites with Next.js, starting from simple ones to more complex projects.