Learn Next.js: A full-stack React Framework thumbnail

{Learn Next.js: A full-stack React Framework}

Routing, API routes, and data fetching, built through a simple crypto app
November 16, 2022
nextjsreactjsbeginner

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. Whether you are creating highly interactive static sites like blogs or creating full-stack web applications like a social media application, Next.js is the way to go! Next.js is the ultimate tool for any React developer to learn and improve their projects. It enhances your React apps by adding more features to it.

NEXTJS HOMEPAGE

Key Features of Next.js

  • Page-based routing (create a page by putting components in /pages)
  • A built-in router (no need to install React Router)
  • API routes (write backend code using Node.js and create full-stack apps)
  • Better SEO
  • And many other...

Understanding Next.js

Let us first understand some of the important features that Next.js provides us with.

Routing

Next.js makes it easier to create routes in our application. We no longer need to install libraries and setup the routes manually like in a React app. In Next.js, a new route gets created automatically as we create a new file in the /pages folder.

Types of Routes

All the files named index.js will automatically be routed to the root of the directory.

  • pages/index.js → http://my-domain.com/
  • pages/blog/index.js → http://my-domain.com/blog

If you create a Nested folder structure, the files will also be automatically routed in the same nested way.

  • pages/profile/settings/personal-info.js → http://my-domain.com/profile/settings/personal-info

You can also create Dynamic routes by simply using bracket syntax for the dynamic segment.

  • pages/[username]/settings.js → http://my-domain.com/:username/settings

Linking between pages

Next.js provides a React component called Link that allows you to do the client-side route transitions between pages in your app. You can simply import the Link component and start using directly in your Next.js applications.

import Link from 'next/link'
 
const Navbar = () => {
	return (
		<div>
			<Link href="/">Go to Homepage</Link>
		</div>
	)
}
 
export default Navbar;

API Routes

Next.js provides a solution to build all your APIs within your Next.js application itself. All the files that you create in the pages/api is directly mapped to /api/* and will treated as API endpoint instead of a page.

// pages/api/hello.js
 
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello World' })
}

For example, the above API route /pages/api/hello.js returns a json response with a status code of 200 similar to a Node.js application.

Now, to request the data and use it in the client pages, we can simply use the traditional approach using the useEffect and useState hooks provided in React.

But, Next.js provides us with a hook called useSWR to effectively fetch the data in your application. To learn more about using SWR, you can checkout the SWR docs.

Creating our Next.js app

We will learn all about Next.js by creating a simple Crypto App.

Project setup

We can automatically setup our Next.js application using the create-next-app package. We need to have NPM installed on our systems to use this package.

npx create-next-app 
# or
yarn create next-app 

After the installation is complete, we can start the development server on http://localhost:3000 using npm run dev or yarn dev commands.

Adding styles

Now that you know the basics of Next.js, let us focus on creating our own Next.js application.

Since, we will be focusing on the main application and not the CSS, you can simply add these styles in your styles directory.

/* styles/globals.css */
 
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  background-color: #eff5f5;
}
 
a {
  color: inherit;
  text-decoration: none;
}
 
a:hover {
  text-decoration: underline;
}
 
* {
  box-sizing: border-box;
}
/* styles/Home.module.css */
 
.container {
  padding: 0 2rem;
}
 
.main {
  min-height: 100vh;
  padding: 4rem 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}
/* styles/CoinsList.module.csss */
 
.coinsContainer {
  max-width: 100vw;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
 
.card {
  background-color: white;
  margin: 1rem;
  padding: 0 20px;
  text-align: left;
  color: #497174;
  text-decoration: none;
  border: none;
  border-radius: 10px;
  width: 300px;
}
 
.cardTitle {
  display: flex;
  color: black;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #d0d0d0;
}
 
.cardTitle img {
  width: 30px;
  height: 30px;
}
 
.cardContent {
  border-bottom: 1px solid #d0d0d0;
}
 
.actionLink {
  color: black;
}
/* styles/Navbar.module.css */
 
.navbar {
  width: 100%;
  height: 80px;
  background-color: #eb6440;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
 
.navitems {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 80%;
  height: 100%;
  color: white;
  font-weight: bold;
}
  
.navitems p {
  font-size: 1.5rem;
}
 
.navlinks {
  display: flex;
}
 
.navlinks a {
  margin-left: 20px;
}

Installing the necessary dependencies

We will use Axios library to fetch data about the cryptocurrencies from an API. We will also use the SWR library to fetch the server-side data to our client pages.

npm install axios swr

Creating the Homepage

// pages/index.js -> https://localhost:3000
 
import Head from 'next/head';
import Link from 'next/link';
 
import styles from '../styles/Home.module.css';
 
export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>NextJS Demo</title>
        <meta name="description" content="Crypto app using Next.js" />
      </Head>
  
      <main className={styles.main}>
        <h1>Welcome to the Crypto App!</h1>
 
        <Link href="/coins">View all Cryptocurrencies...</Link>
      </main>
    </div>
  );
}

Next.js provides us with a Head component from the next/head to conveniently add meta data to our webpages. The Head component also provides us with the capability to add different titles and metadata for different pages.

To add the CSS to the components, we need to first import the our styles from the CSS module we had created in our styles directory. We can then add our created styles, by adding the classNames in the {styles.class-name} format.

homepage

Creating the Cryptocurrencies page

// pages/coins/index.js -> https://localhost:3000/coins
 
import Axios from 'axios';
import Head from 'next/head';
 
import styles from '../../styles/CoinsList.module.css';
 
const CoinsList = ({ coinData }) => {
  return (
    <div className={styles.coinsContainer}>
      <Head>
        <title>Crypto Coins | NextJS Demo</title>   
      </Head>
      {coinData.coins.map((coin) => (
        <div className={styles.card} key={coin.id}>
          <div className={styles.cardTitle}>
            <h3>
              {coin.rank}. {coin.name}
            </h3>
            <img src={coin.icon} alt={coin.name} />
          </div>
 
          <div className={styles.cardContent}>
            <p>Price: {coin.price}</p>
            <p>Market Cap: {coin.marketCap}</p>
            <p>Daily Change: {coin.priceChange1d}%</p>
          </div>
          
          <p>
            <a
              href={`${coin.exp[0]}`}
              className={styles.actionLink}
              target="blank"
            >
              Learn More...
            </a>
          </p>
        </div>
      ))}
    </div>
  );
};
 
export const getStaticProps = async () => {
  const data = await Axios.get(
    'https://api.coinstats.app/public/v1/coins?skip=0'
  );
 
  return {
    props: {
      coinData: data.data,
    },
  };
};
 
export default CoinsList;

Here, we have simply fetched the cryptocurrencies data using Axios library. We have used getStaticProps to fetch our data and provided it to the CoinsList component. We can then map through each coin and display it on our app.

getStaticProps vs getServerSideProps

Next.js recommends Static Generation whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request. For this, you need to export an async function called getStaticProps.

If a page uses Server-side Rendering, the page HTML is generated on each request. This can be done using getServerSideProps . This function will be called by the server on every request. It will be slower because the page cannot be cached by a CDN, but the pre-rendered page will always be up-to-date.

currenciesPage

Creating Profile page

Finally to understand how the API routes are implemented in Next.js we will create a simple Profile Page.

// pages/api/profile-data.js
 
export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}
// pages/profile/index.js -> https://localhost:3000/profile
 
import Head from 'next/head';
import useSWR from 'swr';
 
const fetcher = (...args) => fetch(...args).then((res) => res.json());
 
const Profile = () => {
  const { data, error } = useSWR('/api/profile-data', fetcher);
  if (error) return <div>Failed to load</div>;
  if (!data) return <div>Loading...</div>;
 
  return (
    <div>
      <Head>
        <title>Profile | NextJS Demo</title>
      </Head>
      <h2>Welcome {data.name}!</h2>
    </div>
  );
};
 
export default Profile;

By using the useSWR hook from the swr library, we can fetch the name that is provided as a json data from the API we had created in /api/hello.js.

profile

404 Page

Next.js allows us to create our own custom 404 Pages. To create our own Page not Found page we need to create a file pages/404.js. Now if the users route to a random unknown path, they will be shown the 404 page.

// pages/404.js -> https://localhost:3000/some-random-route/123
 
import Link from 'next/link';
 
const PageNotFound = () => {
  return (
    <div>
      <h2>Oops! Looks like this page does not exist!</h2>
      <Link href="/">Return back to Home page...</Link>
    </div>
  );
};
 
export default PageNotFound;
404

Creating a Navbar

// components/Navbar.js
 
import Link from 'next/link';
 
import styles from '../styles/Navbar.module.css';
 
const Navbar = () => {
  return (
    <div className={styles.navbar}>
      <div className={styles.navitems}>
        <p>CryptoApp</p>
        <div className={styles.navlinks}>
          <Link href="/">Home</Link>
          <Link href="/coins">Cryptocurrencies</Link>
          <Link href="/profile">Profile</Link>
        </div>
      </div>
    </div>
  );
};
 
export default Navbar;

We have created the Navbar, but where do we import it? If we import in the pages/index.js it will be visible only on the Homepage and not in the other pages. So, we will create a Layout component to display the Navbar on all the pages we have created.

// components/Layout.js
 
import Navbar from './Navbar';
 
const Layout = ({ children }) => {
  return (
    <>
      <Navbar />
      <div>{children}</div>
    </>
  );
};
 
export default Layout;

In the above code we will import the Navbar, and create a basic layout. The Navbar will be visible on the top on every page, and all the other pages and components we had created earlier (children) will be rendered below the Navbar.

Now, we will import the Layout component in the pages/_app.js and wrap the children components within the Layout component.

// pages/_app.js
 
import '../styles/globals.css'
 
import Layout from '../components/Layout';
 
function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}
 
export default MyApp
navbar 1
navbar 2

Conclusion

Congratulations! You have made it to the end of this article!!!

We have created an entire application using Next.js. We have learnt how to create pages and routes in our application, fetch data in our application and also learnt how to add styles. If you have followed everything in this article, you can now start using Next in your own React projects.

For more information, you can also visit the official Next.js documentation.

You can find the complete code here: Learn Next.js Github