Getting Started With Next.js and Create Your First Application Using Next.js
Next which supports Hot Module Replacement
- API routes to build API endpoints with Serverless Functions
- Fully extendable
This is among:
Output screen after running the app. Similarly,
pages/posts/first-post.jsis associated with the
/posts/first-postroute.
Go ahead and try adding some by urself we are not reloading the page actually.!
Next.js is the powerful react framework that solves different problems like Server Side Rendering, Pre-rendering, SEO, etc. But it always keeps you very close with awesome library — react to develop your application. Next.js is bundled with plenty of built-in classes for better Developer Experience like:
- Page based routing system (with support to custom routing)
- Pre-rendering, both static generation and server side rendering
- Client-side routing with optimized prefetching
- Built-in CSS and Sass support
- Development Environment which supports hot module replacement
Next.js has been trusted by the very big companies in the world. If you are from the react background, then you will find almost everything similar to react while using Next.js. Today, in this article, we will be developing a very simple Next.js application with some design and layouts and we will fetch api using pre-rendering.
Let’s build the app then!
1. Create Project Directory
Let’s create a project directory and name it as hello_next. Open up the project directory on your favorite Code Editor and I would prefer vscode for it.
2. Initialize package.json
Open up the terminal containing the project directory and run following command that will create package.json file, which includes our project dependencies and scripts. Including -y on the command will generate the package file with all the defaults.
npm init -y
3. Install React, React Dom and Next
Now, we install React, React Dom and Next for our project with the following command.
npm install --save react react-dom next
3. Change Scripts of package.json
Add these scripts to the scripts section of package.json. Then, we can run the code with the command npm run dev.
//package.json"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
4. Routing
Next.js has file-system based router built on concept of pages. So, we need to create a folder named pages and whatever the name of the file would be, the same would be the name of route. You will know better about it when we make use of this concept.
We will be creating two pages, one would be the home page and another would be about page.
So, let’s create index.js file inside the pages directory with simple welcome text.
//pages/index.jsconst Index = () => {
return (
<div>
<h1>Welcome to Next Application</h1>
</div>
);
}export default Index;
Now, create about.js file inside same pages directory with following code.
//pages/about.jsconst About = () => {
return(
<div>
<h1>
About NextJS
</h1>
<p>Application to Demonstrate NextJS Basics</p>
</div>
);
}export default About;
If you haven’t run the project yet, then run with npm run dev command. you will see the home page because index.js will take ‘/’ route. For now add ‘/about’ to the url to navigate to about page. We will build a navigation sections with bootstrap later on.
5. Components
We can create the components in Next.js same as of react. So, let’s create Navbar component and the Layout component which includes layout of our simple demo application.
First, let’s create the Navbar Component. So, we create folder named components to the root of the project. Inside components folder, create navbar.js file which includes navigation menu for the project and also include bootstrap CDN for better design. Also, we are going to implement styled jsx just to demonstrate how they are used in next.js. These styles would be available to only this component.
//components/navbar.jsimport Link from 'next/link';const Navbar = () => {
return(
<div>
<ul>
<li><Link href="/"><a>Home</a></Link></li>
<li><Link href="/about"><a>About</a></Link></li>
</ul><style jsx>{`
ul {
background: #333;
color: #fff;
list-style: none;
display: flex;
}ul li {
font-size: 22px;
margin-right: 50px;
}ul li a {
color: #fff;
text-decoration: none;
}
`}</style>
</div>
);
}export default Navbar;
You can see how router navigation is done with next/link in the above code.
Now, we need to create a layout for the project. So, we will create layout.js file inside the components folder and we will use the navbar component in layouts.
//components/layout.jsimport Head from 'next/head';
import Navbar from './navbar';
const Layout = (props) => {
return(
<div>
<Head>
<title>Hello Next.js</title>
<link rel="stylesheet" href="" />
</Head>
<Navbar />
<div className="container">
{props.children}
</div>
</div>
);
}
export default Layout;
Now, lets modify our index.js and about.js to make use of the available layout.
We are going to apply very important feature of Next.js, which is `getInitialProps`.
getInitialProps enables server-side rendering in a page and allows us to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. It is an async function that can be added to any page as a static method. Let’s take a look at how we are going to fetch data for sample music api and display them in our home page. Also, we are going to add isomorphic-unfetch to fetch the api.
npm install --save isomorphic-unfetch
After adding this let’s modify our index.js. The full and final code in this page is done below.
//pages/index.jsimport Layout from '../components/layout';
import fetch from 'isomorphic-unfetch';const Index = ({musicData}) => {
console.log(musicData)
return (
<Layout>
<div>
<h1>Welcome to Next Application</h1>
<h3>Songs List</h3>
{musicData.map((item, i) => {
return (
<li key={i}>{item.title}</li>
)
})}
</div>
</Layout>
);
}Index.getInitialProps = async function() {
const response = await fetch(``);
const result = await response.json();
return { musicData: result.data }
}export default Index;
Also, let’s modify our about.js. The full and final code in this page is done below.
//pages/about.jsimport Layout from '../components/layout';const About = () => {
return(
<Layout>
<div>
<h1>
About NextJS
</h1>
<p>Application to Demonstrate NextJS Basics</p>
</div>
</Layout>
);
}export default About;
Demo
Now, our very simple Next.js application is ready to run. You can find the data fetched through the sample api and the pages as shown below:
Summary
Next.js automatically optimizes your application for the best performance by code splitting, client-side navigation, and prefetching (in production).This is very simple application developed using Next.js. You can gain the basic knowledge about how to install and work with next.js through this article.
You create routes as files under
pages and use the built-in
Link component. No routing libraries are required.
You can learn more about the
Link component in the API reference documentation and routing in general in the routing documentation.