Open In App

Getting Started with Next JS

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?

What Features Does NextJS Not Have?

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:

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

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.

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:

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

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

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:

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

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.

Article Tags :