A Delve into Next.js
Published: 2024-05-09 07:40:24

Next.js, developed by Vercel, is an open-source web development framework that offers server-side rendering and static website generation for React-based web applications.

Next.js is a powerful framework for developing static and Server-Side Rendering (SSR) apps, known for its excellent SEO features, making it popular among developers.
While creating a Next.js app is one thing, deploying it to leverage its SEO and SSR capabilities is another challenge.

By the end of this article, you'll have the know-how to deploy your Next.js app using the CLIs provided by Netlify and Vercel. Prior experience with GitHub, React.js, and Next.js is assumed. 

Features of Next.Js
Next.js aims to provide an exceptional developer experience with numerous built-in features, including:
- Automatic code splitting to enhance page load speed
- Client-side routing with optimized prefetching
- Intuitive page-based routing system, supporting dynamic routes
- Support for both static generation (SSG) and server-side rendering (SSR) on a per-page basis
- Built-in support for CSS and Sass, as well as compatibility with any CSS-in-JS library
- Development environment with rapid refresh support
- API routes for constructing API endpoints using serverless functions
- Full extensibility.

Creating a simple blog with Next.js
To write JavaScript on the server side, you'll require Node.js installed (version 10.13 or newer). Use the following command to initiate a Next.js project:

```
npx create-next-app demo-for-next
```

Once the package installation is complete, navigate to your application directory and open it with a code editor (preferably vscode).

![file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90603g6tq2b7z6hp4406.png)

A folder named "pages" has been created, containing several files, including index.js, _app.js, and api>hello.js. Each .js file represents a specific endpoint of your web application, with the exception of _app.js, which serves as a customizable app component used to initialize pages into their respective endpoints. We'll delve into _app.js separately in the future. By default, index.js serves as the root route ("/"), and you can create nested routes by placing a .js file (e.g., "hello.js") within a folder named "api", resulting in an endpoint of "/api/hello". This setup allows for easy configuration of different routes simply by creating each page (with the file name serving as the path, excluding the ".js" extension).

Enter the command below in your terminal to display the output of your Next.js app in a browser:
```
npm run dev
```

Then visit localhost:3000 to view the pre-built pages generated by Next.js. Initially, you'll see the content from index.js at the root path. You can also navigate to the /api/hello route to view the content of hello.js.

![localhost preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yusfm8f3c8ssskcp6no7.png)


Now, let's begin creating our basic blog example. Open the "index.js" file located in the "pages" folder. We'll customize the content at the root path to serve as our sample blog's homepage. I've created a simple layout using the styles provided by Next.js.

```

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>My Little Blog</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to My Blog
        </h1>
        <div className={styles.grid}>
          <Link href="./blog1">
            <a className={styles.card}>
              <h3>Blog 1</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat vehicula felis eget feugiat. Nullam mattis feugiat massa, id consectetur dolor pellentesque eget. Praesent non varius est, at rutrum nisl. Maecenas feugiat vitae quam et imperdiet. Nam vulputate volutpat metus, mollis faucibus nisi eleifend ac. Integer egestas libero odio, eget ultrices leo condimentum eu.</p>
            </a>
          </Link>

          <Link href="./blog2">
            <a className={styles.card}>
              <h3>Blog 2</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat vehicula felis eget feugiat. Nullam mattis feugiat massa, id consectetur dolor pellentesque eget. Praesent non varius est, at rutrum nisl. Maecenas feugiat vitae quam et imperdiet. Nam vulputate volutpat metus, mollis faucibus nisi eleifend ac. Integer egestas libero odio, eget ultrices leo condimentum eu.</p>
            </a>
          </Link>
        </div>
      </main>
    </div>
  )
}

```

Note the imported Link from "next/link". This feature enables client-side routing for our server-side rendered app. It means our app doesn't need to make requests to the server every time the user changes the URL or endpoint path. Simply use the <Link> tag to wrap around the HTML element (in this case, an anchor tag) you want to navigate to, and Next.js handles the rest. Here, we're using it to navigate to each blog post page from our homepage.

Next, we'll create two blog posts for demonstration purposes, and we'll discuss how to make our app dynamic with Next.js in the future.

```

import styles from '../styles/Home.module.css';
import Link from 'next/link';

export default function Blog1(){
    return (
        <div className={styles.main}>
            <h1 className={styles.title}>HELLO, THIS IS BLOG 1</h1>
            <p className={styles.card} style={{width: "50%"}}>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat vehicula felis eget feugiat. Nullam mattis feugiat massa, id consectetur dolor pellentesque eget. Praesent non varius est, at rutrum nisl. Maecenas feugiat vitae quam et imperdiet. Nam vulputate volutpat metus, mollis faucibus nisi eleifend ac. Integer egestas libero odio, eget ultrices leo condimentum eu. Vestibulum quis accumsan enim. Aenean sed justo tortor. Duis tincidunt elit ut vulputate commodo. Maecenas at laoreet felis, quis euismod quam. Nulla at nibh sit amet ipsum tincidunt lacinia ac eu mauris.

                Nam ornare congue egestas. In sed urna convallis, efficitur mauris et, eleifend sem. Vivamus a tempus risus. Donec dignissim nec arcu vel laoreet. Aenean ultrices porta diam. Duis vel eros vehicula, ornare felis eu, eleifend diam. Praesent sit amet erat sed libero feugiat molestie ut nec felis.

                Vivamus laoreet ex sed ligula vestibulum congue. Pellentesque porttitor tellus ut odio pulvinar sagittis. Morbi viverra tristique dignissim. Proin interdum luctus semper. Nulla at pulvinar orci. Curabitur sed dapibus sem. Mauris rhoncus aliquam felis sit amet feugiat. Curabitur tincidunt facilisis semper.

                Etiam sit amet risus et orci tincidunt posuere. Integer fermentum pellentesque velit nec venenatis. Etiam eleifend laoreet rhoncus. Aenean cursus tortor neque, in varius eros hendrerit quis. Maecenas eu porttitor eros. Integer quis fringilla mauris. Morbi pulvinar mattis justo a elementum. Phasellus aliquam auctor orci sit amet hendrerit. In ante nisl, pretium vitae volutpat et, semper nec ex. Phasellus leo arcu, congue eu convallis nec, varius quis sem. Quisque sodales neque blandit massa mollis bibendum. Cras nec molestie velit. Nullam vel consequat libero, non porta ipsum. Sed sit amet libero mi. Etiam iaculis ipsum sed porttitor gravida. Duis nec pretium ante.

                Sed ullamcorper accumsan mi, at dignissim dolor vestibulum in. Quisque diam orci, congue in sagittis a, dapibus et odio. Praesent convallis augue non fringilla maximus. Aliquam varius ipsum ac cursus tempus. Donec lacus purus, tincidunt id ultrices ut, sollicitudin sit amet erat. Curabitur a gravida lorem, id feugiat orci. Curabitur ut pretium nulla, at pulvinar libero. Aliquam blandit neque blandit felis interdum, sed dictum ligula porttitor. Mauris condimentum ut massa in placerat. Suspendisse rhoncus finibus leo ut sagittis. Cras quis odio nec ante gravida viverra ut ac dui. Nunc tristique dictum metus vitae pharetra. Vivamus in leo vel urna sagittis efficitur sit amet a ante. Nulla pellentesque malesuada imperdiet. Phasellus non lacus consectetur, lobortis orci ac, gravida nisl. Vivamus eget lobortis elit.
            </p>
            <Link href="/">
                <a>Back to home</a>
            </Link>
        </div>
        );
}

```

```

import styles from '../styles/Home.module.css';
import Link from "next/link";

export default function Blog2(){
    return (
        <div className={styles.main}>
            <h1 className={styles.title}>HELLO, THIS IS BLOG 2</h1>
            <p className={styles.card} style={{width: "50%"}}>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget mauris lectus. Proin pulvinar ipsum id augue efficitur, vel imperdiet magna ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. In id nisi velit. Donec commodo blandit orci in gravida. Mauris non purus vel erat ornare bibendum porttitor a elit. Nullam maximus neque tortor, non lobortis felis posuere eu. Praesent orci turpis, pulvinar sit amet dolor at, viverra sollicitudin erat.

                Integer aliquam ornare mauris sed sagittis. Aenean interdum lectus consectetur elementum dapibus. Pellentesque non ipsum imperdiet, commodo elit sed, ornare purus. Sed lacus ipsum, tempor at elementum rhoncus, tempor ac nisi. Morbi tellus ex, malesuada aliquet ultrices a, aliquam eu erat. Nulla rhoncus et orci at scelerisque. Donec dignissim ac nibh ac varius.

                Nulla mollis lacinia urna nec feugiat. Mauris libero ipsum, eleifend quis dolor ac, vulputate porta odio. Suspendisse semper felis nec elementum elementum. Maecenas placerat lorem eget odio mattis finibus. Etiam auctor mauris eget massa tristique, non luctus leo suscipit. In egestas mauris in lectus facilisis, porta semper felis lobortis. Suspendisse elit nibh, euismod et velit id, ornare accumsan massa. Donec ut ante in nunc ornare gravida. In dictum urna sed laoreet sollicitudin. Duis vel scelerisque neque, vitae dapibus tellus. Curabitur volutpat libero a interdum porttitor. Praesent purus est, consectetur iaculis convallis ut, congue fringilla est. Maecenas venenatis risus lectus, a pellentesque magna ullamcorper ac. Nulla tempus et metus et dictum. Aenean neque metus, fringilla et condimentum sit amet, aliquam sed ipsum.

                In a ipsum egestas, congue nulla nec, dictum nisi. Ut libero urna, posuere eget ipsum sed, tempus commodo metus. Ut cursus enim id ex cursus, eget laoreet mi sodales. Proin nulla turpis, consequat vitae ultrices eget, suscipit non libero. Aliquam porttitor varius sem in pellentesque. Vivamus volutpat neque erat, a ullamcorper tortor ullamcorper eu. Duis a magna pulvinar, imperdiet ligula sit amet, pharetra urna. Nam lobortis lectus at velit ultricies, sit amet pellentesque sapien cursus. Donec posuere ex tellus, at auctor enim aliquam eget. Duis iaculis lorem vitae efficitur pretium. In sit amet quam egestas, dapibus quam vel, placerat lacus. Integer ut commodo felis. Aliquam tristique ex eu quam tincidunt suscipit. Fusce porta blandit urna. Vestibulum quis porta nibh, at dictum odio. Sed ut pulvinar quam.

                Vivamus ultrices, sem ut lacinia pellentesque, nibh sem posuere orci, in aliquam nisi enim id tellus. Quisque elementum laoreet lectus in gravida. Morbi vitae egestas libero. Cras erat dolor, faucibus sed leo eget, lobortis pharetra leo. Aenean nec sapien lorem. Ut facilisis mauris quam, at commodo diam ultricies ut. Nam eget lectus vitae nulla sagittis porttitor non at ligula. Aenean porta est vitae mi pulvinar scelerisque. Ut vel orci tellus. Aenean tincidunt quis elit ut porttitor. Suspendisse nisi nisi, sodales at ante at, efficitur consequat mi.

                Curabitur tempus cursus nulla quis cursus. Morbi pretium fringilla posuere. Nullam tristique ex at justo ornare elementum. Vestibulum blandit quis urna eget gravida. Sed dapibus hendrerit ante, a dictum diam maximus sed. Vivamus accumsan odio et finibus varius. Pellentesque fringilla erat purus. Sed lacinia purus in consectetur consequat. Donec nec blandit neque. Quisque lobortis rutrum quam ac pulvinar. Nunc semper tempus lectus, consequat eleifend nunc feugiat quis. Sed volutpat erat a mauris auctor vulputate. Vestibulum ipsum ligula, porttitor eu massa convallis, scelerisque consequat massa.

                Cras non condimentum risus, quis sollicitudin neque. Vivamus aliquet hendrerit urna vel tincidunt. Praesent tristique scelerisque tristique. Vivamus risus dui, ornare non lobortis ut, pharetra ullamcorper tellus. Nunc quis urna egestas, accumsan mauris eget, sodales metus. Fusce nec dignissim purus. Suspendisse ultrices pretium tellus, ultrices efficitur lorem semper eu. Quisque laoreet, lorem placerat scelerisque feugiat, ante felis pulvinar libero, id pharetra turpis eros ut nisi. Etiam dictum nulla at lectus rhoncus condimentum. Phasellus a quam augue. Nullam ornare nisi eget elit rhoncus sagittis.
            </p>
            <Link href="/">
                <a>Back to home</a>
            </Link>
        </div>
        );
}

```

Click on the link labeled "Back to home" to navigate around, and you'll notice that the refresh button doesn't cause the page to flicker, indicating that the page isn't being re-rendered, similar to React.

That concludes this demonstration. We'll delve into more in-depth topics on Next.js, such as dynamic routing, getInitialProps, and others, in future articles.