🚀 This repository aimed to contains 500 nextjs interview questions & answers with exmample.
No | Contents |
---|---|
1 | Common |
2 | Pages Router |
3 | App Router |
4 | Others |
-
Next.js is a React framework for building full-stack web applications.
-
Using command
npx create-next-app@latest
-
It contains React components that are automatically routed based on their file name.
-
Routing based on the file structure in the
pages or app
directory. -
- Server Side Rendering (SSR): Next.js allows rendering React components on the server before sending them to the client, improving performance and SEO.
- Static Site Generation (SSG): It pre-renders pages at build time, useful for blogs or e-commerce sites.
- API Routes: You can build a backend using API routes in the same codebase without needing an external server.
- File Based Routing: Next.js automatically creates routes based on the file structure inside the pages directory.
- Client Side Rendering (CSR): Like React, Next.js also supports traditional client-side rendering.
- Incremental Side Rendering:
- Image Optimization: Built-in image optimization capabilities that reduce image sizes and enhance loading times.
- Automatic Code Splitting: Next.js splits the code into smaller bundles, which are loaded only when required, improving performance.
- TypeScript Support: Native support for TypeScript, enabling strict typing and better developer experience.
- Incremental Static Regeneration (ISR): Pages can be statically generated at runtime and updated incrementally.
- Fast Refresh: Provides an instant feedback loop while coding, similar to React's hot reloading.
-
Feature Next.js React.js Rendering Supports Server-Side Rendering (SSR), Static Site Generation (SSG), and Client-Side Rendering (CSR). Only supports Client-Side Rendering (CSR) by default. Routing Built-in file-based routing system. Automatically generates routes based on the folder structure. No built-in routing. Requires libraries like React Router. SEO Excellent for SEO as it supports SSR and SSG, allowing pre-rendered content to be indexed by search engines. Limited SEO capabilities due to client-side rendering. Additional work is needed for SEO optimization. Performance Faster initial page load due to SSR, automatic code splitting, and static generation. May have slower page loads for large apps since everything is rendered on the client. Configuration Minimal configuration required. Comes with SSR, SSG, and routing out of the box. Requires manual setup for SSR, routing, and other advanced features. Learning Curve Slightly steeper due to built-in advanced features like SSR, SSG, and API routes. Easier to learn initially, but requires additional tools for SSR and routing. API Routes Built-in API routes that can handle backend logic within the same project. No support for API routes; requires external tools for backend development. Code Splitting Automatically splits code into smaller bundles, loading only what’s needed for a specific page. Requires manual code splitting or use of lazy loading to optimize performance. Deployment Optimized for easy deployment on platforms like Vercel (creators of Next.js) and supports serverless functions. Deployment typically requires additional configuration for optimized hosting and SSR. Image Optimization Has a built-in Image component for automatic image resizing and optimization. Does not provide image optimization; developers need third-party libraries for that. -
Incremental Static Regeneration is a technique in Next.js that allows you to update static pages at runtime without rebuilding the entire site. This feature introduces a seamless way to serve both static and dynamic content by revalidating and regenerating pages in the background.
-
A component for client-side navigation between pages.
import Link from 'next/link' <Link href="/">Home</Link> <Link href="/about">About</Link>
-
A hook that allows access to the router object and perform navigation.
-
Using useRouter() hook.
const router = userRouter(); function handleClick() { router.push(`/path`); } <button onClick={handleClick}>Go There</button>;
-
Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
-
Using CSS modules with a .module.css file extension.
-
Pre-rendering pages at build time. If a page uses Static Generation, the page HTML is generated at build time.
-
Rendering pages on each request. If a page uses Server-side Rendering, the page HTML is generated on each request.
-
Re-generating static pages at runtime as traffic comes in.
-
A component that optimizes images for faster loading.
export default function Page() { return ( <Image src={profilePic} alt="Picture of the author" // width={500} automatically provided // height={500} automatically provided // blurDataURL="data:..." automatically provided // placeholder="blur" // Optional blur-up while loading /> ); }
-
A configuration file to customize Next.js settings.
-
By adding a tsconfig.json file.
-
A feature to create API endpoints in the
pages/api
directory. -
By connecting the repository to Vercel and deploying it.
-
Generating HTML for pages in advance, instead of on each request.
-
Static generation pre-renders at build time, SSR pre-renders on each request.
-
There are a few ways you can handle redirects in Next.js. One of them is by configuring redirects in next.config.js.
-
A component for modifying the of a page.
-
A folder for static assets served from the root URL.
-
Using getStaticProps or getServerSideProps.
// getStaticProps export async function getStaticProps() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); const repo = await res.json(); return { props: { repo } }; } export default function Page({ repo }) { return repo.stargazers_count; }
// getServerSideProps export async function getServerSideProps() { // Fetch data from external API const res = await fetch("https://api.github.com/repos/vercel/next.js"); const repo = await res.json(); // Pass data to the page via props return { props: { repo } }; } export default function Page({ repo }) { return ( <main> <p>{repo.stargazers_count}</p> </main> ); }
-
A feature to load components or modules dynamically.
const ComponentA = dynamic(() => import("../components/A")); const ComponentB = dynamic(() => import("../components/B"));
-
By adding them to .env.local and accessing via process.env.
-
Determines how to handle missing paths, with true, false, or ‘blocking’.
-
A way to customize the server-side behavior, e.g., with Express.
-
To manage the document head for meta tags, title, etc.
-
To export a static version of the Next.js app.
-
By using the built-in font optimization feature.
-
Port 3000.
-
By configuring headers in next.config.js.
-
A feature for quick feedback when editing React components.
-
By adding a babel.config.js file.
-
By configuring i18n settings in next.config.js.
-
A development mode that highlights potential problems in an application.
-
A single router instance accessible across the application.
-
Create a directory into pages directory & create index file.
pages/index.jsx // / pages/blog/index.jsx // /blog
-
By using square brackets in the filename
pages/blogs/[id].js.pages // /blogs/1, /blogs/2, /blogs/... blogs/[id]/index.js // /blogs/1, /blogs/2, /blogs/... app/products[id]/page.jsx // /products/1, /products/2, /products/...
-
A custom App component that initializes pages and can add global styles or layout components.
-
A custom Document component that allows customization of the HTML document structure.
-
By adding a 404.js file in the pages directory.
-
getStaticProps fetches data at build time, while getServerSideProps fetches data on each request.
-
A function used for static site generation to fetch data at build time.
export async function getStaticProps() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); const repo = await res.json(); return { props: { repo } }; } export default function Page({ repo }) { return repo.stargazers_count; }
-
A function used for server-side rendering to fetch data on each request.
export async function getServerSideProps() { // Fetch data from external API const res = await fetch("https://api.github.com/repos/vercel/next.js"); const repo = await res.json(); // Pass data to the page via props return { props: { repo } }; } export default function Page({ repo }) { return ( <main> <p>{repo.stargazers_count}</p> </main> ); }
-
A function used with getStaticProps to specify dynamic routes to be pre-rendered.
export async function getStaticPaths() { return { paths: [ { params: { name: "next.js", }, }, ], }; } export async function getStaticProps() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); const repo = await res.json(); return { props: { repo } }; } export default function Page({ repo }) { return repo.stargazers_count; }
-
By importing the CSS file in _app.js.
-
A hook for handling translations when using i18n.
-
By adding _error.js in the pages directory.
-
Accelerated Mobile Pages, a framework for fast-loading mobile pages.
-
By adding amp attribute to a page component.
-
To optimize and serve images in a Next.js application.
-
For client-side navigation between pages.
-
pages contains routable components, components contains reusable UI components.
-
Using middleware functions in next.config.js.
-
By customizing the webpack configuration in next.config.js.
-
Client-side rendering happens in the browser, server-side rendering happens on the server.
-
Automatically determining if a page can be statically generated.
-
Using useEffect and fetch or other data fetching libraries.
-
Using libraries like NextAuth.js or custom authentication logic.
-
_app.js is for global components, _document.js is for modifying the HTML document structure.
-
By adding files to the pages/api directory.
-
Incremental Static Regeneration, updating static pages after build without redeploying.
-
By extending the Webpack configuration in next.config.js.
-
It provides type definitions for TypeScript support in Next.js.
-
Using the file-based routing system in the pages directory.
-
To enable dynamic imports and code splitting.
"use client"; import { useState } from "react"; import dynamic from "next/dynamic"; // Client Components: const ComponentA = dynamic(() => import("../components/A")); const ComponentB = dynamic(() => import("../components/B")); const ComponentC = dynamic(() => import("../components/C"), { ssr: false }); export default function ClientComponentExample() { const [showMore, setShowMore] = useState(false); return ( <div> {/* Load immediately, but in a separate client bundle */} <ComponentA /> {/* Load on demand, only when/if the condition is met */} {showMore && <ComponentB />} <button onClick={() => setShowMore(!showMore)}>Toggle</button> {/* Load only on the client side */} <ComponentC /> </div> ); }
-
Using the Head component from next/head.
-
To compose multiple plugins in next.config.js.
-
Using client-side form handling or API routes for server-side handling.
-
By creating a Redux store and integrating it with _app.js.
-
To handle routing and navigation within a Next.js app.
-
Using libraries like styled-components or Emotion.
-
By adding a redirects property in next.config.js.
-
By installing sass and importing .scss files in your components.
-
It allows you to specify a base path for the application.
-
By creating a 500.js file in the pages directory.
export default function Custom500() { return <h1>500 - Server-side error occurred</h1>; }
-
It configures whether to include a trailing slash in the URLs.
-
push adds a new entry in the history stack, replace replaces the current entry.
-
It disables server-side rendering for the dynamically imported component.
-
By using plugins like next-pwa and configuring next.config.js.
-
By including the Google Analytics script in _app.js or _document.js.
-
To run code before a request is completed.
-
By setting up Apollo Provider in _app.js and creating a client.
-
Configuration exposed to the browser.
-
Configuration only available on the server side.
-
To customize the error page for HTTP errors.
-
Using useEffect and fetch or any other data-fetching library.
-
To manage SEO metadata in a Next.js application.
-
By installing tailwindcss and configuring it with PostCSS.
-
By installing next-i18next and setting up the configuration in next.config. js.
-
To optimize loading third-party scripts.
-
By using the next/font package or including fonts in the public directory.
-
By using Apollo Client or another GraphQL client.
-
It enables the use of the SWC compiler for minification.
-
To enable composition of multiple plugins in Next.js configuration.
-
An application that uses both static generation and server-side rendering.
-
Create a directory into app directory & create page file.
app/page.jsx // / app/blog/page.jsx // /blog
-
By setting headers in the API route handlers.
-
To map an incoming request path to a different destination path.
-
Using libraries like cookie or js-cookie to set and retrieve cookies.
-
By storing tokens in cookies or local storage and sending them with requests.
-
To configure and enable Progressive Web App features in Next.js.
-
To generate sitemaps for a Next.js application.