What’s Nextjs and where it is used?
Nextjs is an open-source frontend framework based on React and build on top of Node.js. It offers many features that will take a lot of effort and time to implement on React. And currently, Nextjs is used by some companies like Notion, TikTok, Hulu, Nike, Netflix-jobs, and guess what even the site you are reading this blog on is developed using Nextjs.
You can see other companies from their Showcase page.
Features provided by Nextjs
Following is the list of features that you will not get with create-react-app but you can get when you use Nextjs:
- Built-in routing system: lets you create a page just by creating a file of that name inside the
/pages
folder. So no need for react-router-dom; - Easy to implement dynamic routing;
- Two types of pre-rendering. Static generation and Server-side rendering;
- Because of the pre-rendering options, Nextjs improves the SEO of your web app;
- Built-in Image optimization through its specific component;
- Built-in Link tag to link pages or redirect to other sites;
- Fast refresh: provides a live editing experience;
- Built-in CSS and Typescript support;
- Option to create API routes to provide backend;
- Get detailed analytics of your site by just enabling Next Analytics on Vercel;
- Built-in support for i18n routes which is internationalized routing.
Brief explanation of some features that are widely used
Before we learn more about other features let’s see how you can create a fresh Next.js project.
But before you start you should have Node.js and npm installed.
Open your terminal and type the following command:
npx create-next-app@latest
If you want to use Typescript you can just add --typescript
at the end as follows:
npx create-next-app@latest --typescript
After the Next app is created you can run:
npm run dev
to start your app on localhost.
Once your app is started you can click the link in your terminal or simply go to your browser and copy-paste the following URL: http://localhost:3000
You will see the following page in your browser:
And the folder structure will look like follows:
File System Routing:
When you open the project’s folder you will see a folder named pages
open that folder and create a new file named about.js
and copy the following code:
import React from "react";
import styles from "../styles/Home.module.css";
export const about = () => {
return (
<div>
<h1 className={styles.title}>This is about page!</h1>
</div>
);
};
The above code is quite simple for anyone having a slight understanding of React.
Now in your index.js copy paste the below code on line number 22 copy paste the following code:
<Link href="/about">
<a className={styles.description}>About</a>
</Link>
In the above code, you are using a Next.js component named Link
which you can import from next/link
. The link component is used to enable transitions between routes. Learn more about Link
from here.
Now if you click about you will be redirected to the About
page.
Dynamic routing:
Implementing dynamic routing is quite easy when using Next.js. You just need to create a folder you want to create dynamic routes for. Here we are using routes
as our folder name.
Inside the routes, folder create a file named [routeid].js
inside the file copy-paste the below code:
import { useRouter } from "next/router";
const Route = () => {
const router = useRouter();
const { routeid } = router.query;
return <p>Route No: {routeid}</p>;
};
export default Route;
In the above code, we are using the useRouter
hook of Next.js which you can import from next/router
. Here we are using the query string object to get the object of the useRouter
to get the query object of the URL.
We are linking our /about
page with dynamic routes so copy and paste the below code in about.js
.
<ul>
<li>
<Link href="/routes/abc">
<a>go to routes id: abc</a>
</Link>
</li>
<li>
<Link href="/routes/256">
<a>go to routes id: 256</a>
</Link>
</li>
<li>
<Link href="/routes/xyz">
<a>go to routes: xyz</a>
</Link>
</li>
<li>
<Link href="/routes/658">
<a>go to routes: 658</a>
</Link>
</li>
</ul>
In the above code, we are using the Link
component as we did in the File System Routing example. Here we are using /abc
or /xyz
or /256
or you can put anything as you wish that is a valid URL to assign it to the query of our routes so when you open /abc
; [routeid].js
will assign it's value to abc so in the router.query
abc will be passed.
You can read more about dynamic routing from here.
Pre Rendering(Static generation):
Static generation is used when you don't need to fetch data from your server whenever the user opens that page i.e. you need to fetch the data only once when the build command runs. SEO is improved if you use static rendering.
To statically render data you need to export the getStaticProps
function on your page as follows:
export async function getStaticProps() {
const res = await fetch("https://someapi.com/route-you-need-to-call");
const data = await res.data();
return {
props: {
data,
},
}
}
In the above code, we are just fetching the data from an API and returning it as props so that we can use it on our page.
You can use any library to fetch the data.
Learn more about getStaticProps
from here.
To statically render dynamic paths you need to use getStaticPaths
read more about it from here.
Pre Rendering(Server side rendering)
Server-side rendering is used when you need to fetch the data from the server every time a user requests that page. So when you use getServerSideProps
data is fetched whenever that page is requested via next/link
or next/router
. Mostly server-side rendering is used when you are dealing with dynamic data.
To render your data on the server side you need to export the getServerSideProps
function on your page as follows:
export async function getServerSideProps() {
const res = await fetch("https://someapi.com/route-you-need-to-call");
const data = await res.data();
return {
props: {
data,
},
}
}
In the above code, we are just fetching the data from an API and returning it as props so that we can use it on our page.
You can use any library to fetch the data.
Learn more about getServerSidePorps
from here.
Image optimization
Next.js’s <Image />
component is built over HTML’s <img />
tag which provides various performance-based optimizations.
You can import the <Image />
component from next/image
.
Learn more about Image Optimization from here.
API Routes
Using API routes you can build your API in your Next app.
To add API routes you need to add the file inside pages/api
so whenever a file is created under api/
will be only on server side so it won’t affect your client side data size.
If you open your hello.js
inside api/
you can see it’s returning a JSON
with status of 200
.
You can learn more about API routes from here.