Getting Started with Next JS
Last Updated :
23 Jul, 2025
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.
Create Your First Next.js 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:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"export": "next export",
"lint": "next lint"
}
- dev: Starts the development server.
- build: Builds the production-ready application.
- start: Starts the production server after building.
- lint: Runs linting checks on your Next.js project files using ESLint.
- 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.
JavaScript
// 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
2. 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).
3. Layouts - A layout is a UI that is shared between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render.
Links and Navigation in Next JS
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
// Filename - index.js
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.
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.
JavaScript
// 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>
);
}
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.
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.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects