Getting started with Next.js (Beginners Guide)

You might have heard that people often talk about something called Next.js with React.js. Let’s first see what Next.js is then we will create a basic Next.js application.

Next.js

Next.js is an open-source web development framework created by Vercel enabling React-based web applications with server-side rendering and generating static websites. (Wikipedia)

People often prefer to use Next.js with React.js if they want to create a website that is more SEO friendly and might need to be ranked on search engines.

Now that we have basic idea we can move towards creating an application using Next.js.

You should know
Before we move further you must have an idea of following:
1. React.js
2. HTML
3. CSS
4. JavaScript

Next.js is very similar to React.js. The major different is the folder structure. You might have created a react application using “npx create-react-app” that gives you a starter template of React.js based website with all initial dependencies. Similarly, Next.js app can be created with this command

npx create-next-app website

Once the execution is completed your website folder will look like this:

Now before moving on coding, let’s understand that what is the purpose of each folder.

node_modoles

You might have seen node_modules in react.js and node.js applications. Node_modules basically contain all the files and sub files of downloaded and default dependencies.

pages

The pages folder contains a folder called API, where we can add files and create server-side logics like connecting our databases etc. The second and third files are similar to react.js index and app.js files. The index.js files also represent the default root route of our page.

public

The public folder will contain all public files that are a bit similar as react.js app. I often add assets>images folder in it and put all images in them.

styles

As the name suggests, styles folder contains all the .css/style sheets.

Other Files

You can also see few other files like .gitignore, package.json that you can read online. The other main file is next.config.js, it is a file with next.js configurations in it.

Now that we have a basic understanding of our next.js website layout, let’s navigate to website folder and run the following command to start our app:

npm run dev

Now if you can see this in console, head to your browser and go to http://localhost:3000 where you can see the starter page.

If you can see this screen, it means everything is going all fine till now.

Let’s now remove all the root route content and add our own. Your index.js file will now look like this

export default function Home() {return (<div></div>)}

Let’s add some dummy content.

export default function Home() {return (<div><h1>Home Page</h1></div>)}

I prefer to use my own css(styling) so I will remove content inside globals.css in styles folder. I will also change index.js to index.jsx for ease.

Next, I will create another file called about.jsx in pages folder.

import React from "react";function About(){return(<div className="about"></div>)}export default About;

Adding content in about.jsx file.

import React from "react";function About(){return(<div className="about"><h1>About Page</h1><p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dolor et ea laboriosam mollitia cum ab omnis repellat nesciunt aperiam modi, molestiae soluta pariatur quod voluptas eos laborum quo delectus, quae ratione sint consectetur neque in vitae esse. Saepe, unde, amet earum voluptatum dolores aut ullam minima doloribus quaerat debitis similique?</p></div>)}export default About;

Now open the url “http://localhost:3000/about”. You can see the routing was performed automatically and your page will look like this

Now let’s think of a situation, you want to create a page with a route “/user/info”, how will you do it as next.js handles routing by itself?

Well, we can create folders and put files in it. Let’s see an example.

import React from "react";function Info(){return(<div className="info"><h1>Info Page</h1></div>)}export default Info;

info.jsx ⬆

Now navigate to “http://localhost:3000/user/info” in your browser. You will see Info Page written. It means that that everything is working.

Now for example you want a page on “/user” route and you already have a folder “user”, you will not create a file called user you will simply add index.jsx in user folder. All the content of that file will be visible at “/user” route.

Dynamic Routing

Let’s consider another example. You have multiple users, and you want to see their information separately on a different page. Imaging you have 100 users, you will not create 100 different file for each. What you will do is you will create create a dynamic page that will take information from URL i.e. a user id mostly.

Let’s see how we can add a dynamic route.

We will create a folder called view and inside it will add a file call [id].jsx. You might get confused by the file name but it’ll be clearer in a while. Next add content in it.

import React from "react";function ViewUser(){return(<div className="viewUser"><h1>User Details</h1><h5>Id: </h5></div>)}export default ViewUser;

Now if you go to “http://localhost:3000/user/view/1”, you will see a heading “User Details” and “Id:”.

Now what is the use of it. Let’s consider we want to see a user info with user id of “2”, we will navigate to “http://localhost:3000/user/view/2”. Now from the URL we will get “2”, send it to our api and fetch data of user with ID of “2” and display their details. Now how to get ID from URL? Let’s write a code for it.

import React from "react";import { useRouter } from 'next/router'function ViewUser(){const router = useRouter()const { id } = router.queryreturn(<div className="viewUser"><h1>User Details</h1><h5>Id: {id}</h5></div>)}export default ViewUser;

Now here we are using next.js router and importing it. Next in “const { id } = router.query” we are getting the id of user that will be stored in “id” variable and simply we are display it in <h5></h5>.
You can now enter any number/values after /user/view/ and it will return that value in id variable.

Now that we have covered most of the basic routing techniques, learned our about basic structure. Let’s look at how we can create APIs in our Next.js application.

API

I have mentioned that we have a folder called api in our project’s pages folder. That is where we can create APIs.

By default you can see a file called hello.js in our api folder.

Inside hello.js file you will see a function handler. It will handle incoming requests. Let’s modify it for a GET request.

export default function handler(req, res) {if(req.method=='GET'){res.status(200).json({ message: 'Working GET Request' })}else{res.status(404).json({ message: 'Page not Found!' })}}

Now if you navigate to “http://localhost:3000/api/hello” you will see a object with a message “Working GET Request”. Now if someone has used Postman they can test “POST” request as well and it’ll give an object with a message “Page not Found!” with status code of “404”.

Now we have a basic understanding that how we can create APIs. Let’s create an API to fetch user data.

User Info API

First create a folder called “user” in API folder and create another folder inside it called “view”. Next we will create a file in view folder named as “[id].js”. It is similar to the file we create earlier. It is basically a dynamic api route.

Now let’s add code to it.

export default function handler(req, res) {var userArray = [{"id": 1, "name": "Alice"},{"id": 2, "name": "Peter"},{"id": 3, "name": "Harry"}];if(req.method=='GET'){const { id } = req.queryconsole.log(id)var result = userArray.find(user => user.id == id);console.log(result)res.status(200).json({ data: result })}else{res.status(404).json({ message: 'Page not Found!' })}}

Now here we have a dummy data of 3 user. On a GET request we are taking id of user from request url and getting that specific user details using .find function and returning it as a response. You can test the route at “http://localhost:3000/api/user/view/1”.

Integrating our user api in our client-side.

Earlier we made a dynamic route in pages folder in user folder. Lets fetch user details from our API. I will be using axios you can install it using “npm install axios”.

import React, { useEffect, useState } from "react";import { useRouter } from 'next/router'import axios from 'axios';function ViewUser(){var [user, setUser] = useState();const router = useRouter()useEffect(()=>{const { id } = router.queryaxios.get(`http://localhost:3000/api/user/view/${id}`).then((response) =>{console.log(response)setUser(response.data.data)}).catch(err=>console.log(err));}, [])return(<div className="viewUser"><h1>User Details</h1><h5>Id: {user.id}</h5><h5>Name: {user.name}</h5></div>)}export default ViewUser;

Now if you go to “http://localhost:3000/user/view/1” you will see data of “Alice”

We have covered most of the basic topic of Next.js. Next.js is known and a replacement for react.js is because it’s SEO friendly. The last and most talk feature I will be discussing is how to add meta tags on your Next.js applications.

SEO in Next.js

In react.js people have faced SEO problems and often web crawlers are unable to read your website content since it initially has only one div i.e., root and later content is added. Next.js provides the solution. Next.js make your application on build time and keeping it in ready form.

Adding META Tags in Next.js

Next.js provides a method of adding custom meta tags and title for your application. Let’s add few meta tags in our website.

I have added Head tag that is from next and imported on the top in our index.js file in pages folder. Next, I have added few meta tags and enclosed them in <Head></Head>

import Head from "next/head";export default function Home() {return (<div><Head><meta charSet="utf-8" /><title>Next.js website</title><meta name="keywords" content="medium, blog, article, next.js" /><meta name="description" content="Test website for nextjs seo" /></Head><h1>Home Page</h1></div>)}

Now you might have a basic idea of Next.js and you can now start developing Next.js website with little practice.

GitHub repo: MuqtadirBillah/next-started (github.com)

Follow me for more interesting tips and tricks at Musab Abbasi — Medium
You can also find me on LinkedIn and GitHub

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.