d
WE ARE EXPERTS IN TECHNOLOGY

Let’s Work Together

n

StatusNeo

Nextjs

Build Your Own Nextjs Application: A Beginner’s Guide

What is Nextjs?

Next.js is basically an open-source web development React framework that gives us building blocks to create web applications on the server-side. We can also say Nextjs is a full-stack framework for Reactjs as it is built on React which makes building React apps easier and It did not harm React by adding many core features like routing. It has lots of built-in features that help us to solve common problems that occur while building bigger React applications.

Let’s discuss some key features of Nextjs:
  • Automatic file-based routing
  • Server-Side Rendering
  • Build Full-Stack Apps
  • Data Fetching

Automatic file-based routing

Page-based routing is very helpful for SEO and initial load. In React typically we use React Routers for routing on different components but in Nextjs we no need to create router it is automatically done as it has this framework worked in. So, when we create a new file in our pages directory then route is automatically created for that file.

Server-Side Rendering

Server-side rendering is basically our page will be rendered on the server instead of the client. A server-side rendered application speeds up page loading and improves user experience. Server-side rendering is something where HTML is created on every request. Next.js pre-renders every page this means that Next.js generates HTML for each page in advance each generated HTML is associated with minimal JavaScript code necessary for that page.

Build Full-Stack Apps

We can create a Full Stack application with nextjs as we can easily add backend(server-side) code in our nextjs application. We can add features like storing data, getting data, authentication,etc. to our React projects

Data Fetching

Nextjs allows us to fetch data in different ways depending upon our application needs.There are three main data fetching methods those we use in our nextjs application and they have different use cases for rendering data.

  • getStaticProps
  • getStaticPaths
  • getServerSideProps

getStaticProps()

It is used to preloads all the data needed for the given page, it will be request data at the build time. Once the app is built, it won’t refresh the data until another build has been run. It enables the page to be statically generated and will produce fast load times of all the data fetching methods.

  • We can only export getStaticProps from our page files not from component file.
  • It will run only run on build time(during next build).
  • It always runs on the server and never on the client.
  • Its code is completely excluded from the client-side bundle.

Let’s take an example :

function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// revalidation is enabled and a new request comes in
export async function getStaticProps() {

// We are fetching data from local json file
const filePath = path.join(
      process.cwd(),
      "data",
      "blogs.json"
    );

 const jsonData = await fs.readFile(filePath);
 const posts = JSON.parse(jsonData.toString());

  return {
    props: {
      posts,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every second
    revalidate: 1, // In seconds
  }
}

export default Blog

getStaticPaths()

When we export getStaticPaths (Static Site Generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified in getStaticPaths, it must declare a list of paths that will be statically generated.

  •  It can only be exported from a page file.
  • Page must also implement getStaticProps.
  • It is meant for dynamic routes.
  • The data can be publicly cached
  • The information is taken from the filesystem.
export async function getStaticPaths() {
    return {
        Paths: [
            // See path selection below
            { params: { ...} }
        ],

        // See the fallback section below 
        
    };
}

If fallback: ‘false’ then any paths not returned by getStaticPaths will result in a 404 page. This option is useful if you have a small number of paths to create.

If fallback: ‘true’ then the paths that have not been generated at build time will not result in a 404 page.

If fallback: ‘blocking’ then paths that have not been generated at build time will not result in a 404 page. Instead, Next.js will SSR on the first request and return the generated HTML and it will not update generated pages by default.

getServerSideProps()

The getServerSideProps method fetches data every time a user requests the page and this is useful if you want to fetch data that changes often, and have the page update to show the most current data.. It will fetch the data before sending the page to the client  It is slower as compared to getStaticProps as the page is being rendered on every request.

  • It can only be exported from page file.
  • Great for SEO as data is rendered before it reaches the client.
  • Its code is excluded from the client-side bundle.

Let’s take an example:

export async function getServerSideProps(context) {
  const res = await fetch(`https://posts`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true, //An optional boolean value to allow the page to return a 404 status and page.
    }
  }

  return {
    props: {data}, // will be passed to the page component as props
  }
}

The context  parameter is an object containing following keys :

  • params: If this page uses a dynamic routeparams contains the route parameters. If the page name is [id].js , then params will look like { id: ... }.
  • reqThe HTTP IncomingMessage object.
  • resThe HTTP response object.
  • query: An object representing the query string.
  • previewpreview is true if the page is in the Preview Mode and false otherwise.
  • previewData: The preview data set by setPreviewData.
  • resolvedUrl: A normalized version of the request URL that strips the _next/data prefix for client transitions and includes original query values.
  • locale contains the active locale (if enabled).
  • locales contains all supported locales (if enabled).
  • defaultLocale contains the configured default locale (if enabled).

Lets Create a nextjs app

For creating nextjs app we need to run this.

npx create-next-app my-next-project

In our package.json we currently find four main scripts listed there

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "lint": "next lint"
}

Now a new directory my-next-project will be created in our main directory. Let’s cd into it

cd my-next-project

For running our nextjs app we need to run

npm run dev

Conclusion

In this blog, we have covered the basics of Nextjs and some important methods that are used in Nextjs.

For more interesting blogs visit- StatusNeo Blogs

Thanks for reading, Be excited for next blogs.

I am always eager to learn new tech stacks to overcome my challenges in every field. I love playing games, bike riding, and recharging in nature.

Comments

  • May 22, 2023

    I am a student of BAK College. The recent paper competition gave me a lot of headaches, and I checked a lot of information. Finally, after reading your article, it suddenly dawned on me that I can still have such an idea. grateful. But I still have some questions, hope you can help me.

  • June 4, 2023

    I may need your help. I tried many ways but couldn’t solve it, but after reading your article, I think you have a way to help me. I’m looking forward for your reply. Thanks.

Add Comment