DEV Community

thakur-sahab999
thakur-sahab999

Posted on

Next Js Tutorial

What is Next JS ?

Before moving on learning about Next Js we should know what it is
Next.js is a popular open-source framework for building React applications that allows developers to create server-rendered React applications with ease.

Why Did we used NextJs ?

It provides a set of tools and features that make building and deploying modern web applications more efficient, such as:

Server-side rendering: Next.js supports server-side rendering (SSR) out of the box, which means that the initial HTML is generated on the server and sent to the client, resulting in faster page loads and better SEO.

Automatic code splitting: Next.js automatically splits the code into smaller chunks, so only the code needed for each page is loaded, reducing the initial load time of the application.

Static site generation: Next.js allows for static site generation (SSG), which pre-renders pages at build time, resulting in even faster load times and reduced server load.

API routes: Next.js provides an easy way to create API routes, allowing for easy integration with external data sources.

Built-in CSS support: Next.js has built-in support for styling using CSS modules or styled-components, making it easier to write and maintain CSS for your application.

Overall, Next.js makes it easier and faster to build and deploy modern web applications, while providing features that improve performance, SEO, and development experience.

Prerequsites of learning Next Js:

Before diving into learning Next.js, it's recommended that you have a solid foundation in the following technologies:

HTML and CSS: Next.js is built on top of React, which requires a solid understanding of HTML and CSS to build responsive, well-designed web applications.

JavaScript: Next.js is a JavaScript framework, so you should have a good understanding of the language and its fundamentals, including variables, functions, arrays, objects, loops, and conditional statements.

React: Next.js is built on top of React, so you should have a good understanding of React's core concepts, including components, state, props, and the virtual DOM.

Node.js: Next.js uses Node.js to run server-side rendering and other server-side tasks. You should have a good understanding of Node.js and how to use it to create web applications.

Git: Git is a version control system that is commonly used for managing code repositories. You should be familiar with Git and how to use it to manage your code.

Additionally, it's recommended that you have some experience building web applications before diving into Next.js. While Next.js provides many benefits over vanilla React, it can still be complex, so having experience building web applications can help you better understand the concepts and tools used in Next.js.

System Prerequsites

To get started with Next.js, you'll need to ensure that your system meets the following prerequisites:

Node.js: Next.js is built on top of Node.js, so you'll need to have Node.js installed on your system. You can download the latest version of Node.js from the official website: Node.js

NPM: NPM (Node Package Manager) is used to manage the dependencies for your Next.js project. It comes bundled with Node.js, so you should have it installed by default.

Git: Git is a version control system that is commonly used for managing code repositories. You should have Git installed on your system to manage your Next.js project.

Lets Create a NextJs App

Here's a step-by-step guide to building a Next.js app that shows images in cards, implements infinite scrolling, and uses Server Side Rendering to fetch data using getServerSideProps

Step 1: Set Up the Project
To get started, create a new Next.js project by running the following commands:

npx create-next-app

my-app cd my-app

Step 2: Install Dependencies
Next, install the following dependencies:

npm install axios react-infinite-scroll-component tailwindcss

We'll use the axios library to make HTTP requests to the API, react-infinite-scroll-component to implement infinite scrolling, and tailwindcss to style our components.

Step 3: Create Image Card Component
Create a new file called ImageCard.js in the components directory and add the following code:

code:

import React from 'react';

function ImageCard({ image }) {
  return (
    <div className="rounded overflow-hidden shadow-lg">
      <img src={image.urls.regular} alt={image.alt_description} />
      <div className="px-6 py-4">
        <div className="font-bold text-xl mb-2">{image.user.username}</div>
      </div>
    </div>
  );
}

export default ImageCard;

Enter fullscreen mode Exit fullscreen mode

This component takes an image object as a prop and displays it in a card with the photographer's name.

Step 4: Create Infinite Scroll Component
Create a new file called InfiniteScrollImages.js in the components directory and add the following code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import InfiniteScroll from 'react-infinite-scroll-component';
import ImageCard from './ImageCard';

function InfiniteScrollImages() {
  const [images, setImages] = useState([]);
  const [page, setPage] = useState(1);

  useEffect(() => {
    fetchImages();
  }, []);

  const fetchImages = async () => {
    const response = await axios.get(`https://api.unsplash.com/photos`, {
      params: {
        client_id: '<YOUR_API_KEY>',
        page: page,
        per_page: 9,
      },
    });

    setImages((prevImages) => [...prevImages, ...response.data]);
    setPage((prevPage) => prevPage + 1);
  };

  return (
    <InfiniteScroll
      dataLength={images.length}
      next={fetchImages}
      hasMore={true}
      loader={<h4>Loading...</h4>}
    >
      <div className="grid grid-cols-3 gap-4">
        {images.map((image) => (
          <ImageCard key={image.id} image={image} />
        ))}
      </div>
    </InfiniteScroll>
  );
}

export default InfiniteScrollImages;

Enter fullscreen mode Exit fullscreen mode

This component uses the useState hook to store the images and the page number. We use the useEffect hook to fetch the images when the component mounts. The fetchImages function makes an HTTP request to the Unsplash API to get the images and updates the state with the new images and the new page number. Finally, the InfiniteScroll component wraps the image cards and fetches more images when the user scrolls to the bottom of the page.

Step 5: Create Index Page

export async function getServerSideProps() {
    const { data } = await 
    axios.get(`https://api.unsplash.com/photos/random`, {
      params: {
        client_id: '<YOUR_API_KEY>',
        count: 9,
      },
  });

  return {
    props: {
      initialImages: data,
    },
  };
}

export default function Home({ initialImages }) {
  return (
    <div className="container mx-auto my-8">
      <h1 className="text-4xl font-bold mb-8">Infinite Scroll Images</h1>
      <InfiniteScrollImages initialImages={initialImages} />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

This page uses the getServerSideProps function to fetch the initial set of images on the server side. We make a request to the Unsplash API to get 9 random images and pass them to the InfiniteScrollImages component as a prop. Finally, we render the InfiniteScrollImages component on the page.

Step 6: Add Tailwind CSS
Next.js comes with built-in support for CSS modules, so we can easily add Tailwind CSS to our project. Create a new file called styles/globals.css and add the following code:

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Then, import this file in the pages/_app.js file:

import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Step 7: Add API Key
To use the Unsplash API, you'll need to create an account and generate an access key. Once you have your access key, replace in the InfiniteScrollImages.js and index.js files with your actual key.

Step 8: Start the Development Server
Finally, start the development server by running the following command:

npm run dev

Visit http://localhost:3000 in your browser to see the app in action.

That's it! You've built a Next.js app that shows images in cards, implements infinite scrolling, and uses Server Side Rendering to fetch data using getServerSideProps.

Push the code to the gitLab/gitHub

Now Lets Deploy It

Step 1: Launch an EC2 Instance
First, launch an EC2 instance using the AWS Management Console. Make sure to select an instance type that meets your needs and configure the security group to allow incoming traffic on port 80 (HTTP) and 443 (HTTPS).

Step 2: Connect to the Instance
Once the instance is launched, connect to it using SSH. You can use the ssh command in your terminal or use a tool like PuTTY if you're on a Windows machine.

ssh -i <PATH_TO_PRIVATE_KEY> <USER>@<PUBLIC_IP_ADDRESS>

Enter fullscreen mode Exit fullscreen mode

Replace , , and with the appropriate values.

Step 3: Install Nginx
Next, install Nginx on the instance using the following commands:

sudo apt update
sudo apt install nginx
Enter fullscreen mode Exit fullscreen mode

Step 4: Clone the project
Next, install Nginx on the instance using the following commands:

cd /var/www/html
sudo git clone <repo url>
cd my-app
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Nginx
Create a new file at /etc/nginx/sites-available/default and add the following configuration:

server {
        server_name www.DOMAINNAME.com DOMAINNAME.com;

        index index.html index.htm;
        root /var/www/html/my-app; #Make sure your using the full path

        # Serve any static assets with NGINX
        location /_next/static {
            alias /var/www/html/my-app/.next/static;
            add_header Cache-Control "public, max-age=3600, immutable";
        }

        location / {
            try_files $uri.html $uri/index.html # only serve html files from this dir
            @public
            @nextjs;
            add_header Cache-Control "public, max-age=3600";
        }

        location @public {
            add_header Cache-Control "public, max-age=3600";
        }

        location / {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }

        location @nextjs {
            # reverse proxy for next server
            proxy_pass http://localhost:3000; #Don't forget to update your port number
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }

        listen 80 default_server;
        listen [::]:80;
}


Enter fullscreen mode Exit fullscreen mode

Replace with your domain name or public IP address.

This configuration tells Nginx to listen on port 80 and proxy requests to the Next.js app running on localhost:3000.

Step 5: Restart Nginx
Once you've added the configuration, restart Nginx using the following command:

sudo systemctl restart nginx

Step 6: Install PM2
Install PM2 globally on the instance using the following command:

sudo npm install -g pm2

Step 7: Build and Start the Next.js App
In the root directory of your Next.js app, build the production version of the app:

cd /var/www/html/my-app
npm run build
Enter fullscreen mode Exit fullscreen mode

Then, start the app using PM2:

pm2 start npm --name "<APP_NAME>" -- start

Replace with a name for your app.

Step 8: Save the PM2 Configuration
Save the PM2 configuration to ensure that your app will be restarted if the instance is restarted:

pm2 save

Step 9: Access the App
Visit your domain name or public IP address in your browser to access the app. Nginx will proxy requests to the Next.js app running on localhost:3000.

Congratulations, you've successfully deployed your Next.js app on an AWS EC2 instance using Nginx as a reverse proxy server and PM2 as a process manager!

Top comments (0)