Open In App

Getting Started with Next JS

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

NextJS is an open-source React framework for building full-stack web applications ( created and maintained by Vercel ). You can use React Components to build user interfaces, and NextJS for additional features and optimizations. It is built on top of Server Components, which allows you to render server-rendered React components to the client. This means your pages can be more interactive and dynamic, while still being fast and performant. One of its notable features is the NextJS App Router, which facilitates routing within your application. This article will dive into NextJS App Router, its components, and implementation, and provide a code example and a brief output.

What Features NextJS Gives You?

  • Server-side Rendering (SSR) and Static Site Generation (SSG): Next.js empowers you to choose how your pages are generated. SSR allows for dynamic content personalized per user, while SSG offers pre-rendered static pages for lightning-fast load times.
  • Automatic Code-Splitting: Next.js intelligently breaks down your application into smaller bundles, ensuring only the necessary code is loaded for each page, resulting in a faster user experience.
  • File-Based Routing: Routing is intuitive in Next.js. Each file in the pages directory corresponds to a route in your application, making the structure clear and easy to manage.
  • Built-in Data Fetching: Next.js provides functions like getStaticProps and getServerSideProps for fetching data at build time or on each request, giving you flexibility for different content types.
  • Automatic Image Optimization: Next.js automatically optimizes images for various screen sizes and devices, improving website performance and user experience.
  • TypeScript Support: Next.js seamlessly integrates with TypeScript, providing type safety and improved development experience for TypeScript users.
  • Static Site Generation (SSG): Next.js supports static site generation, where pages can be pre-built at build time, enhancing performance and reducing server load.

What Features Does NextJS Not Have?

  • Built-in State Management: While Next.js is tightly integrated with React, it doesn’t come with built-in state management solutions. Developers can use libraries like Redux or React Context for state management.
  • Built-in Styling Solution: Next.js doesn’t include a built-in solution for styling components. Developers can choose from various styling solutions like CSS Modules, Styled Components, or Tailwind CSS.

What is the NextJS App router?

The NextJS App Router is a core component of the Next.js framework that handles routing within your application. It enables you to define and manage the routes your application will respond to. Next.js follows a file-based routing system, making it an intuitive and efficient way to structure your application’s navigation. It offers various components and features to create robust and flexible routing in your Next.js application.

How to Create a NextJS App?

To create a NextJS app, you can use the following steps:

Step 1: Install NodeJS if you haven’t already. Open a terminal and run the following command to create a new Next.js app:

npx create-next-app my-next-app

Step 2: On installation, you’ll see the following prompts:

What is your project named? my-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like to use `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias (@/*)? No / Yes
What import alias would you like configured? @/*

Step 3: Navigate into your newly created app directory:

cd my-next-app

Step 4: Start the development server:

npm run dev

Step 5: Open your browser and visit http://localhost:3000 to see your Next.js app running.

NextJS Scripts:

Next.js provides several scripts to manage your application:

  • dev: Starts the development server.
  • build: Builds the production-ready application.
  • start: Starts the production server after building.
  • export: Exports the application as a static site.

Add TypeScript to NextJS:

To add TypeScript to a Next.js app:

npm install --save-dev typescript @types/react @types/node

Rename your .js files to .tsx or .ts. Next.js will automatically detect TypeScript and provide type-checking support

Creating a Simple Page in Next JS:

This example creates a basic page that displays “Hello, World!”. This page component is named index.js and is located in the pages directory.

pages/index.js

Javascript
import React from 'react';

export default function Home() {
  return (
    <div>
      <h1>Hello, World!</h1>
    </div>
  );
}

Pages and Routes in Next JS

1. Routing – Next.js uses a file-based structure router where folders define the routes. A special page.js file is used to make route segments

Pages – A page is a UI that is Unique to a route. Use nested folders to define routes and a page.js file to make it publicly accessible.

  • pages/index.js corresponds to the homepage (/).
  • pages/about.js corresponds to the about page (/about).

Layouts – A layout is a UI that is shared between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render.

Linking and Navigating – Next.js provides two primary methods for linking and navigating between routes:

  • Using <Link> component The <Link> is a built-in component that extends the HTML <a> tag to provide prefetching and client-side navigation between routes
  • Using the useRouter hook The useRouter hook allows you to programmatically change routes. This hook can be used only in client components
Javascript
import Link from 'next/link';

const HomePage = () => (
  <div>
    <Link href="/about">
      <a>About Page</a>
    </Link>
  </div>
);

export default HomePage;

Navigation and routing use Prefetching, Caching, Partial rendering, Soft navigation, and Back and forward navigation.

Route Groups in Next JS

A Route group can be created by wrapping the folder name with parenthesis (folderName) which helps in

  • Organize the routes without affecting the URLs.
  • To create a group of related routes together.

Dynamic Routes – A Dynamic segment can be created by wrapping a folder name in square brackets [folderName]

Loading UI and Streaming – It is a special file `loading.js` that helps to create meaningful loading UI with React suspense.

Streaming allows us to break down the page’s HTML into small chunks and progressively send those chunks from the server to the client.

Error Handling – The error.js file convention allows to handle unexpected runtime errors in nested routes

Route Handlers – Route Handlers allows you to create custom route handlers for a given route using the web request and response.

Route Handlers are defined in a route.js | ts

SEO in Next JS:

NextJS offers built-in SEO optimizations such as server-side rendering and automatic code splitting, which can improve search engine visibility. Developers can also use meta tags and structured data to further enhance SEO.

API Routes in Next JS:

NextJS allows you to create API routes to handle server-side logic separately from your main application logic. API routes are stored in the pages/API directory and can be accessed via HTTP requests.

Data fetching in Next JS

There are four ways to fetch data

  • on the server, with a `fetch`
  • on the server, with third-party libraries
  • on the client, with route handlers
  • on the client, with third-party libraries

Fetching Data on the server with fetch

Fetching Data on the server with fetch, Next Js extends the native fetch web API to allow you to configure the caching and revalidating behavior for each request on the server. fetch with async / await in server components.

Fetching data on the Server with third-party libraries

In cases where you’re using a third-party library that doesn’t support or expose fetch (for example, a database, CMS, or ORM client), you can configure the caching and revalidating behavior of those requests using the Route Segment Config Option and React’s cache function.

Fetching Data on the Client with Route Handlers

If you need to fetch data in a client component, you can call a Route Handler from the client. Route Handlers execute on the server and return the data to the client. This is useful when you don’t want to expose sensitive information to the client, such as API tokens.

Fetching Data on the Client with third-party libraries

Fetching Data on the Client with third-party libraries using SWR and React Query. These libraries provide their APIs for memoizing requests, caching, revalidating, and mutating data.

Requesting Data in Next JS:

  • Client-side: Next.js integrates well with libraries like fetch or axios for making API requests directly from the browser. This approach is ideal for fetching data that doesn’t require server-side processing.
  • Server-side: Functions like getStaticProps and getServerSideProps enable you to fetch data on the server before the page is rendered. This is useful for dynamic content that needs to be personalized for each user.
  • getStaticProps vs. getServerSideProps:
  • getStaticProps: This function fetches data at build time, making your pages statically generated. This is ideal for content that rarely changes and prioritizes fast load times.
  • getServerSideProps: This function fetches data on each request, making your pages server-rendered. This provides the most dynamic experience but might have a slight performance overhead compared to getStaticProps.
  • Caching Data – Caching stores data so it doesn’t need to be re-fetched from the data source for every request.
  • Revalidating Data – Revalidating data is a process of purging the cache data and fetching the latest data. cached data can be revalidated in two ways.
  • Time-based revalidation and On-demand revalidation.

Exmaple: Fetching Data with getStaticProps: This example fetches a list of posts from an API and displays them on the page. The getStaticProps function fetches data before the page is rendered on the server.

pages/posts.js

Javascript
import React from 'react';

export async function getStaticProps() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts/');
  const data = await response.json();

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

export default function Posts({ posts }) {
  return (
    <div>
      <h1>List of Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

Conclusion

Remember to check the official NextJS documentation and release notes for any specific changes and improvements in version 13 and any new routing features. The framework may have evolved since my last update.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads