Next.js Interview Questions and Answers
Routing, rendering modes, data fetching and deployment on Next.js.
Whether you are preparing for entry-level Next.js interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.
1 Explain SSR, SSG, ISR and CSR in Next.js. Medium
These describe when HTML is produced. CSR ships a minimal shell plus a JS bundle; the browser fetches data and renders, so first paint is slower and SEO weaker, but navigation feels app-like. SSR generates HTML on each request, giving fresh crawlable content at the cost of server work and higher time to first byte. SSG renders at build time and serves the same HTML from a CDN, which is fastest and cheapest but only suits content that rarely changes. ISR is static generation with revalidation: pages are served statically and regenerated in the background after revalidate seconds, combining speed with freshness.
const res = await fetch(url, { next: { revalidate: 60 } });
Use SSR for personalised or real-time pages, SSG and ISR for blogs and marketing, and CSR for dashboards behind auth. In the App Router, per-route segment config such as dynamic and revalidate selects the mode.
2 What are the main differences between the App Router and the Pages Router? Medium
The Pages Router uses files under pages/. Each file exports a default component, data comes from getStaticProps, getServerSideProps or getStaticPaths, and _app and _document customise the shell.
The App Router uses folders under app/ with page.tsx, layout.tsx, loading.tsx and error.tsx, and is built on React Server Components. Key differences: nested layouts preserve state across navigation, fetching happens directly in async server components with automatic request memoisation, streaming with Suspense is first-class, and client components are opt-in with "use client". Route handlers replace API routes.
The App Router is the recommended default for new projects; the Pages Router remains supported and many existing apps use it. You can run both in one project during migration, but a page and an App Router route cannot share the same path. Choose the App Router for new work unless a dependency still assumes the Pages conventions.
3 What is the difference between Server Components and Client Components? Medium
In the App Router components are Server Components by default. They run only on the server, can be async, can read databases or secrets directly, and send no JavaScript to the browser beyond the rendered output. They cannot use state, effects, browser APIs or event handlers.
Client Components are opted in with "use client" at the top of a file. They run on the server for the initial HTML and then hydrate in the browser, so they can use useState, useEffect, refs and event handlers. A "use client" boundary marks the module and everything it imports as client code, so keep boundaries low in the tree to minimise the bundle.
Server Components can render Client Components and pass serialisable props. Client Components cannot import Server Components, but they can receive them as children. Practically, fetch data in server components and keep interactive leaves client-side, passing only the data they need.
4 How does data fetching and caching work in the App Router? Medium
You fetch inside async Server Components using the extended fetch:
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 60, tags: ['posts'] },
});
By default fetch is cached and deduplicated for the lifetime of a request; cache: 'no-store' opts out, and next.revalidate sets an ISR window. revalidatePath('/posts') and revalidateTag('posts') purge caches on demand, typically from a Server Action or route handler after a mutation.
Because components render on the server, data loading is colocated and can be parallelised; wrap slow parts in Suspense to stream. Avoid the old client-side useEffect pattern unless data must be live and user-specific. generateStaticParams pre-renders dynamic routes at build time.
Each route segment can tune caching with export const dynamic = 'force-dynamic' or export const revalidate. Getting these settings right is the main source of stale-data bugs.
5 How do dynamic routes and generateStaticParams work? Medium
Dynamic segments use bracket folders: app/blog/[slug]/page.tsx receives params as a prop, which is a Promise in recent versions. Catch-all routes use [...slug] and optional catch-all uses [[...slug]].
generateStaticParams runs at build time and returns an array of param objects so those pages are pre-rendered:
export async function generateStaticParams() {
const posts = await getPosts();
return posts.map(p => ({ slug: p.slug }));
}
export const dynamicParams = true;
With dynamicParams true, pages not returned at build time are generated on first request and cached; setting it false returns 404 for unknown params. Combined with ISR, the generated pages can revalidate over time. generateMetadata({ params }) gives per-page SEO using the same params.
The older Pages Router equivalent was getStaticPaths with getStaticProps. The App Router model is more flexible because params flow naturally into server components and streaming.
6 What is Next.js middleware and when should you use it? Medium
Middleware in middleware.ts at the project root runs before a request is completed, on the Edge runtime, and can rewrite, redirect, set headers or return a response directly. It is matched with a matcher config or conditional logic.
export function middleware(req: NextRequest) {
if (!req.cookies.get('token')) {
return NextResponse.redirect(new URL('/login', req.url));
}
}
export const config = { matcher: ['/dashboard/:path*'] };
Common uses are auth gating, A/B testing via rewrites, locale detection, bot filtering and security headers. Constraints: it runs on every matched request, so keep it fast and avoid large dependencies. It cannot use Node APIs or query a database directly on the Edge runtime, and it is not a substitute for authorising data access inside routes.
Because middleware runs before caching, rewrites can change which cached page is served. Use it for coarse redirects and header logic, not data fetching.
7 What is the purpose of the `pages or app` directory in Next.js? Medium
The pages and app directories in Next.js represent the routing and layout backbone of the application. Next.js uses file-system based routing, meaning your filesystem structure directly maps to public URL paths:
### 1. The Modern app/ Directory (App Router):
Introduced in Next.js 13+, built entirely on React Server Components:
- Folder-based: Every folder represents a route segment (e.g.
app/blog/page.tsx->/blog). - Special Filenames:
page.tsx: The leaf UI unique to that route.layout.tsx: Shared UI that wraps child pages and preserves state across navigations.loading.tsx: Instant loading skeleton wrapped in React Suspense.error.tsx: React Error Boundary for isolated error recovery.route.ts: API endpoint handler (GET,POST, etc.).
### 2. The Legacy pages/ Directory (Pages Router):
- Every file exported as default React component in
pages/maps directly to a URL route (pages/about.js->/about). - Relies on lifecycle data-fetching methods:
getStaticProps,getServerSideProps, andgetStaticPaths.
8 What is file based routing in Next.js? Medium
File-based routing is an architectural pattern where application URL routes are inferred automatically from the folder and file hierarchy on the filesystem, eliminating the need to maintain an imperative routing registry (like react-router-dom route tables).
### How It Works in Practice:
- Static Routes:
app/contact/page.tsxmaps to/contact. - Dynamic Segment Routes: Folders wrapped in square brackets match dynamic variables:
app/products/[id]/page.tsx matches /products/123 or /products/shoes.
- Catch-All Segments:
app/docs/[...slug]/page.tsxmatches/docs/setup/install/macos. - Route Groups: Folders surrounded by parentheses
app/(marketing)/about/page.tsxorganize code without appearing in the URL path (/about). - Parallel Routes & Intercepting Routes: Slots like
@modaland(..)photo/[id]enable complex UI patterns like modal overlays with sharable URLs.
### Advantages:
Reduces configuration errors, makes codebase navigation intuitive for teams, and enables automatic code-splitting per route.
9 What are the key features of Next.js? Medium
- 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.
10 What are the differences between Next.js and React.js? Medium
| 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. |
11 What is the difference between client-side and server-side rendering in Next.js? Medium
Client-side rendering (CSR) means that the browser fetches the JavaScript and renders the page on the client side, while server-side rendering (SSR) means that the server generates the HTML and sends it to the client.
12 What is the `metadata` export in the App Router and how do you use it? Medium
The App Router supports a metadata export (or metadata.js/ts) to define route-level metadata like title, description, open graph tags and robots. You can export a static object or an async function that returns metadata.
// app/blog/[slug]/page.js
export const metadata = {
title: "Blog Post",
description: "A useful blog post",
};
export default function PostPage() {
/* ... */
}
13 What is `generateStaticParams` and when should you use it? Medium
generateStaticParams is used in the App Router to statically generate dynamic routes at build time (SSG). Return an array of param objects for routes like [slug] so Next.js can pre-render those pages.
// app/blog/[slug]/page.js
export async function generateStaticParams() {
const posts = await fetch("https://api.example.com/posts").then((r) =>
r.json()
);
return posts.map((p) => ({ slug: p.slug }));
}
14 How do fetch cache options work in the App Router? Medium
The fetch API in server components supports caching controls via { next: { revalidate } } and cache modes like cache: 'no-store' or cache: 'force-cache'. Use no-store for always-fresh data and force-cache to reuse cached responses.
const res = await fetch("https://api.example.com/data", {
cache: "no-store",
});
// or
const res2 = await fetch("/api/data", { next: { revalidate: 60 } });
15 What does the `dynamic` export do in the App Router? Medium
Exporting dynamic controls how a route is rendered: 'force-dynamic', 'force-static', or 'auto'. Use it to override Next.js detection — for example, force dynamic when you need per-request rendering.
// app/dashboard/page.js
export const dynamic = "force-dynamic";
16 How do you set head metadata per-route with `head.js` / `head.tsx`? Medium
In the App Router you can create a head.js or head.tsx file inside a route segment to return <head> elements (title, meta, link) for that segment. This is preferred for complex/head-only components.
// app/about/head.js
export default function Head() {
return (
<>
<title>About Us</title>
<meta name="description" content="About page" />
</>
);
}
17 What is the useRouter hook in Next.js? Medium
A hook that allows access to the router object and perform navigation. The useRouter hook allows you to programmatically change routes inside client components.
18 What is the difference between push and replace in useRouter? Medium
The push method adds a new entry to the browser's history stack, while replace replaces the current entry in the history stack.
const router = useRouter();
// Pushes a new route
router.push("/new-route");
// Replaces the current route
router.replace("/new-route");
19 How do you navigate programmatically in Next.js? Medium
Using useRouter() hook.
const router = useRouter();
function handleClick() {
router.push(`/path`);
}
<button onClick={handleClick}>Go There</button>;
jsx
router.push(href: string, { scroll: boolean })
20 How do you enable TypeScript in a Next.js project? Medium
Next.js provides built-in, zero-configuration TypeScript support out of the box:
### 1. In a New Project:
Pass the --typescript flag when bootstrapping:
npx create-next-app@latest my-app --typescript
### 2. In an Existing JavaScript Project:
- Create an empty
tsconfig.jsonin your project root:
touch tsconfig.json
- Run the Next.js development server:
npm run dev
- Next.js detects the
tsconfig.jsonfile and automatically prompts you to install the necessary type packages:
npm install --save-dev typescript @types/react @types/node @types/react-dom
- Next.js automatically populates
tsconfig.jsonwith recommended production defaults and generatesnext-env.d.tsto ensure full Next.js type declarations.
21 What is API Routes in Next.js? Medium
A feature to create API endpoints in the pages/api or app/api directory. It allow you to create custom request handlers for a given route using the Web Request and Response APIs.
22 What is the public folder in Next.js? Medium
The public directory located at the root of a Next.js project serves static assets directly from the root domain path without going through Webpack or build bundling pipelines.
### Directory Structure Example:
my-next-app/
├── public/
│ ├── favicon.ico --> Accessible at https://example.com/favicon.ico
│ ├── robots.txt --> Accessible at https://example.com/robots.txt
│ ├── sitemap.xml --> Accessible at https://example.com/sitemap.xml
│ └── images/
│ └── hero.webp --> Accessible at https://example.com/images/hero.webp
### Usage in Code:
Refer to assets starting with a forward slash (/):
import Image from 'next/image';
export function HeroBanner() {
return <Image src="/images/hero.webp" alt="Hero Banner" width={800} height={400} />;
}
### Important Security Rules:
- Never put secret files, private keys, or server code in
publicbecause every file inside is publicly downloadable. - Assets in
publicshould have static names; dynamic assets produced at runtime should be stored in S3/Cloud Storage or handled via API responses.
23 What is dynamic import in Next.js? Medium
A feature to load components or modules dynamically.
const ComponentA = dynamic(() => import("../components/A"));
const ComponentB = dynamic(() => import("../components/B"));
24 How do you handle environment variables in Next.js? Medium
Next.js has built-in support for environment variables managed through .env files with strict client/server boundary isolation:
### File Priority Hierarchy:
.env.development.local/.env.production.local(Local overrides, ignored by git).env.local(Always loaded, ignored by git).env.development/.env.production(Environment specific).env(Base defaults)
### Server vs Client Access Rules:
- Server-Only Variables (Default & Secure):
Any variable without a prefix is only accessible in Node.js server runtimes (Server Components, Route Handlers, getServerSideProps):
DATABASE_URL=postgresql://user:secret@localhost:5432/db
STRIPE_SECRET_KEY=sk_live_12345
Attempting to read process.env.STRIPE_SECRET_KEY in browser code returns undefined.
- Client-Exposed Variables (
NEXT_PUBLIC_):
To expose a variable to browser JavaScript bundles, prefix it with NEXT_PUBLIC_:
NEXT_PUBLIC_ANALYTICS_ID=UA-98765432-1
NEXT_PUBLIC_API_URL=https://api.example.com
*Security Warning: Never prefix private database credentials or API secrets with NEXT_PUBLIC_.*
25 What is next.config.js? Medium
A configuration file to customize Next.js settings.
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
};
module.exports = nextConfig;
26 How do you add component-level CSS in Next.js? Medium
Using CSS modules with a .module.css file extension.
// styles.module.css
.example {
color: red;
font-size:18px;
}
// Component.js
import styles from './styles.module.css';
export default function Component() {
return <div className={styles.example}>Hello World!</div>;
}
27 What is server side rendering (SSR) in Next.js? Medium
Rendering pages on each request. If a page uses Server-side Rendering, the page HTML is generated on each request.
export async function getServerSideProps() {
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 <p>{repo.stargazers_count} Stars</p>;
}
28 What is static site generation (SSG) in Next.js? Medium
Pre-rendering pages at build time. If a page uses Static Generation, the page HTML is generated 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 <p>{repo.stargazers_count} Stars</p>;
}
29 What is the difference between static site generation and server side rendering? Medium
Both Static Site Generation (SSG) and Server-Side Rendering (SSR) are pre-rendering techniques in Next.js, but differ in when the HTML is rendered:
| Criterion | Static Site Generation (SSG) | Server-Side Rendering (SSR) |
| :--- | :--- | :--- |
| When Rendered | At build time (next build) or via ISR | On every incoming HTTP request |
| Response Latency | Extremely fast (served directly from CDN edge) | Slower (waits for server computation & DB queries) |
| Server Overhead | Zero origin server compute required per visit | Consumes server CPU/RAM on every user request |
| Dynamic Content | Best for content that changes infrequently (blogs, docs) | Best for personalized dashboards, live data feeds |
| Next.js Implementation | Server Components with cached fetch or getStaticProps | Server Components with cache: 'no-store' or getServerSideProps |
### Architectural Recommendation:
Use SSG / ISR whenever possible for maximum SEO performance, low server hosting costs, and instant page loads. Reserve SSR for pages requiring user authentication, dynamic cookies, or real-time query parameters.
30 What is pre-rendering in Next.js? Medium
Generating HTML for pages in advance, instead of on each request.
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 <p>{repo.stargazers_count} Stars</p>;
}
31 What is incremental static regeneration (ISR) in Next.js? Medium
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.
export async function getStaticProps() {
const res = await fetch("https://api.github.com/repos/vercel/next.js");
const repo = await res.json();
return { props: { repo }, revalidate: 1 };
}
32 How do you deploy a Next.js app to Vercel? Medium
Vercel is the creator and maintainer of Next.js, providing an optimized zero-configuration deployment experience:
### Step-by-Step Deployment:
- Push Code to Git:
Push your repository to GitHub, GitLab, or Bitbucket.
- Connect to Vercel:
Log in to vercel.com and click "Add New Project".
- Import Git Repository:
Select your repository from the list. Vercel automatically detects Next.js, configures the build command (next build), output directory (.next), and install command (npm install).
- Configure Environment Variables:
Add production variables (database URLs, API tokens) under the Environment Variables tab.
- Click Deploy:
Vercel compiles your application, deploys static assets to global edge networks, and provisions serverless and edge functions automatically.
### CLI Deployment:
You can also deploy directly from your local terminal using Vercel CLI:
npm install -g vercel
vercel
33 How do you handle redirects in Next.js? Medium
There are a few ways you can handle redirects in Next.js. One of them is by configuring redirects in next.config.js.
module.exports = {
async redirects() {
return [
{
source: "/about",
destination: "/about-us",
permanent: true,
},
];
},
};
34 What is the Head component in Next.js? Medium
A component for modifying the of a page.
import Head from "next/head";
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>;
35 What is the next/head package used for? Medium
To manage the document head for meta tags, title,description, og etc.
import Head from "next/head";
export default function Home() {
return (
<div>
<Head>
<title>My page title</title>
<meta name="description" content="My description" />
</Head>
<h1>Hello World!</h1>
</div>
);
}
36 How do you add custom headers in Next.js? Medium
Custom HTTP headers (such as CORS permissions, Cache-Control policies, or security headers like Content-Security-Policy and X-Frame-Options) can be configured in next.config.js:
// next.config.js
module.exports = {
async headers() {
return [
{
// Apply headers to all API routes
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: '*' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE,OPTIONS' },
{ key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization' },
],
},
{
// Apply strict security headers to all pages
source: '/(.*)',
headers: [
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
],
},
];
},
};
Alternatively, in Next.js App Router, headers can be dynamically appended inside Middleware (middleware.ts).
37 What is the use of next export command? Medium
Historically, next export was the CLI command used to export a Next.js application into pure static HTML/CSS/JS files that could be hosted on any static hosting provider (like GitHub Pages, Nginx, or an AWS S3 bucket).
### Modern Replacement (output: 'export'):
In modern Next.js versions (v13.3+), next export has been deprecated in favor of setting output: 'export' inside next.config.js:
// next.config.js
module.exports = {
output: 'export',
images: {
unoptimized: true, // Static hosts don't have Node.js image optimization
},
};
Running npm run build with this configuration generates an out/ directory containing standalone HTML and static assets.
### Limitations of Static Export:
Features requiring an active Node.js server (such as dynamic getServerSideProps, Server Actions, API routes with runtime streaming, and incremental regeneration) are not supported in pure static exports.
38 How do you optimize fonts in Next.js? Medium
Next.js includes the built-in next/font module, which automatically optimizes typography and removes external network requests for zero layout shift:
### Core Benefits:
- Self-Hosting: Automatically downloads Google Fonts at build time and hosts them locally with your deployment assets. No requests are sent to Google by the user's browser (improving privacy and GDPR compliance).
- Zero Layout Shift (CLS = 0): Injects size-adjust CSS fallbacks to match the proportions of fallback system fonts while custom fonts download.
### Implementation Example:
// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
});
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
);
}
You can also use next/font/local to optimize custom .woff2 font files stored in your project.
39 How do you enable custom fonts in Next.js? Medium
By using the next/font package to optimize and load custom fonts.
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
return (
<main className={inter.className}>
<h1>Hello World!</h1>
</main>
);
}
40 What is the purpose of next-env.d.ts? Medium
next-env.d.ts is an auto-generated TypeScript declaration file placed at the root of a Next.js project.
### What It Does:
It contains TypeScript reference directives ensuring that the TypeScript compiler recognizes Next.js specific ambient types:
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
### Why You Should Never Edit It:
Next.js inspects and regenerates next-env.d.ts whenever you run next dev or next build. It informs TypeScript about:
- Next.js global types (e.g.
process.envaugmentations). - Asset imports (allowing you to
import logo from './logo.png'without type errors). - CSS module typing (
*.module.css).
Always commit this file to Git, but do not make manual edits to its contents.
41 What is the purpose of next-compose-plugins? Medium
next-compose-plugins was a popular community utility library used in older Next.js projects to cleanly chain and compose multiple configuration plugins in next.config.js without messy nested function wrapping:
### Example Legacy Syntax:
const withPlugins = require('next-compose-plugins');
const withBundleAnalyzer = require('@next/bundle-analyzer')();
const withPWA = require('next-pwa');
module.exports = withPlugins([
[withBundleAnalyzer],
[withPWA, { pwa: { dest: 'public' } }],
], {
// Base Next.js configuration
reactStrictMode: true,
});
### Modern Status:
In modern Next.js versions, next-compose-plugins is largely unmaintained and can conflict with modern async Next.js configurations. Modern practice is to wrap configurations directly or use standard function composition:
module.exports = withBundleAnalyzer(withPWA(nextConfig));
42 How do you add polyfills in Next.js? Medium
Next.js automatically provides polyfills for widely used modern ECMAScript features (such as Promise, fetch, Object.assign, Symbol, and URL) targeting browsers that have >0.5% global usage.
### Adding Custom Polyfills:
If your application must support rare or legacy browser APIs:
- In App Router (
app/layout.tsx):
Import the required polyfill at the very top of your root layout or a client component:
// app/layout.tsx
import 'core-js/features/array/at';
import 'resize-observer-polyfill';
- In Pages Router (
pages/_app.js):
Import the polyfill at the top of _app.js before any other application code runs.
- Conditional Polyfill Script:
Use next/script with strategy="beforeInteractive" to load external polyfills (such as Polyfill.io or self-hosted bundles) before React hydrates.
43 What is static optimization in Next.js? Medium
Automatic Static Optimization is a core Next.js feature where the build system automatically analyzes each page to determine whether it can be pre-rendered as pure static HTML:
### How It Works:
- If a page has no dynamic server data requirements (e.g. does not use
getServerSideProps,cache: 'no-store',cookies(), orheaders()), Next.js automatically outputs it as a static HTML file duringnext build. - In the build terminal output, statically optimized pages are flagged with an empty circle
○ (Static)or● (SSG).
### Benefits:
- Instant TTFB: Static pages are cached and served directly from CDN edge caches.
- Zero Compute Cost: No server compute is triggered when visitors access static pages.
- Progressive Hydration: The static HTML renders immediately in the browser, and React attaches event listeners asynchronously.
44 How do you handle internationalization (i18n) in Next.js? Medium
By configuring i18n settings in next.config.js.
module.exports = {
i18n: {
locales: ["en", "fr"],
defaultLocale: "en",
},
};
45 What is React Strict Mode in Next.js? Medium
A development mode only feature for highlighting potential problems in an application. It helps to identify unsafe lifecycles, legacy API usage, and a number of other features.
module.exports = {
reactStrictMode: true,
};
Note: Since Next.js 13.5.1, Strict Mode is true by default with app router, so the above configuration is only necessary for pages. You can still disable Strict Mode by setting reactStrictMode: false.
46 What is a singleton router in Next.js? Medium
In Next.js Pages Router, the Singleton Router refers to the global, shared router instance exported by next/router:
import Router from 'next/router';
// Navigating programmatically outside React component rendering:
Router.push('/dashboard');
### Router Events Lifecycle:
The singleton router allows you to listen to global route transition events across the entire application (useful for displaying top progress bars like NProgress):
Router.events.on('routeChangeStart', (url) => console.log(`Loading: ${url}`));
Router.events.on('routeChangeComplete', () => console.log('Navigation complete'));
### Modern App Router Equivalent:
In modern App Router (next/navigation), the global singleton object is replaced with component-scoped hooks: useRouter(), usePathname(), and useSearchParams().
47 What is next/script used for? Medium
The next/script component is used to load external scripts in a Next.js application. It provides features like loading scripts asynchronously, deferring execution, and controlling script loading behavior.
import Script from "next/script";
export default function Page() {
return (
<>
<Script src="https://example.com/script.js" strategy="lazyOnload" />
<h1>Hello World!</h1>
</>
);
}
48 What is a custom server in Next.js? Medium
A way to customize the server-side behavior, e.g., with Express.
import { createServer } from "http";
import { parse } from "url";
import next from "next";
const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(port);
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? "development" : process.env.NODE_ENV
}`
);
});
49 How do you perform client-side data fetching in Next.js? Medium
Using useEffect and fetch or any other data fetching library like axios,fetch or swr by Next.js team.
import { useState, useEffect } from "react";
function Profile() {
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
fetch("/api/profile")
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, []);
if (isLoading) return <p>Loading...</p>;
if (!data) return <p>No profile data</p>;
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
);
}
50 How do you set up GraphQL in Next.js? Medium
By installing Apollo Client or any other GraphQL client and configuring it in the \_app.js file.
npm install @apollo/client graphql
yarn add @apollo/client graphql
Then, set up Apollo Client in your \_app.js:
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
} from "@apollo/client";
const client = new ApolloClient({
uri: "https://your-graphql-endpoint.com/graphql",
cache: new InMemoryCache(),
});
function MyApp({ Component, pageProps }) {
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
51 What is the use of next-SEO in Next.js? Medium
next-seo is a plugin for managing SEO metadata in Next.js applications, making it easier to set and manage meta tags, Open Graph tags, and other SEO-related elements.
import { DefaultSeo } from "next-seo";
function MyApp({ Component, pageProps }) {
return (
<>
<DefaultSeo
title="My Next.js App"
description="A description of my Next.js app"
openGraph={{
type: "website",
locale: "en_IE",
url: "https://www.example.com/",
site_name: "My Next.js App",
}}
/>
<Component {...pageProps} />
</>
);
}
export default MyApp;
52 How do you handle routing in a Next.js app? Medium
Next.js handles routing through a combination of file-system conventions and client-side navigation components:
### 1. Declarative Navigation (<Link>):
Always use next/link for internal transitions to enable automatic prefetching and prevent full page reloads:
import Link from 'next/link';
<Link href="/about" prefetch={true} className="nav-link">
About Us
</Link>
### 2. Programmatic Navigation:
Use the useRouter hook from next/navigation:
'use client';
import { useRouter } from 'next/navigation';
export function LoginButton() {
const router = useRouter();
const handleLogin = async () => {
await authService.login();
router.push('/dashboard');
router.refresh(); // Refreshes server components
};
return <button onClick={handleLogin}>Log In</button>;
}
### 3. Reading Route Parameters:
useParams(): Access dynamic URL parameters (e.g.id).useSearchParams(): Read query strings (?category=tech).
53 How do you configure next-i18next in Next.js? Medium
By creating a next-i18next.config.js file and initializing it in the app.
// next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: "en",
locales: ["en", "fr"],
},
};
Then, initialize it in your app:
import { appWithTranslation } from "next-i18next";
import nextI18NextConfig from "../next-i18next.config";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(MyApp, nextI18NextConfig);
54 What is SSR: false in dynamic import? Medium
It disables server-side rendering for a dynamically imported component, ensuring it only loads on the client side.
import dynamic from "next/dynamic";
const DynamicComponent = dynamic(() => import("../components/hello"), {
ssr: false,
});
function Home() {
return (
<section>
<Header />
<DynamicComponent />
<Footer />
</section>
);
}
export default Home;
55 How do you add Google Analytics to a Next.js project? Medium
By using the next/script component to load the Google Analytics script.
import Script from "next/script";
export default function MyApp() {
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_TRACKING_ID');
`}
</Script>
</>
);
}
56 How do you add meta tags in Next.js? Medium
Using the Head component from next/head.
import Head from "next/head";
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta
name="viewport"
content="initial-scale=1.0, width=device-width"
/>
<meta property="og:title" content="My page title" key="title" />
</Head>
<p>Hello world!</p>
</div>
);
}
export default IndexPage;
57 How to add sitemap in Next.js app? Medium
To add a sitemap in Next.js app router, you can use the next-sitemap package. First, install it:
npm install next-sitemap
Then, create a next-sitemap.config.js file in the root of your project and configure your sitemap options.
/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: process.env.SITE_URL || "https://example.com",
generateRobotsTxt: true, // (optional)
changefreq: "daily", // (optional)
priority: 0.7, // (optional)
sitemapSize: 7000, // (optional)
exclude: ["/404", "/500"], // (optional)
robotsTxtOptions: {
policies: [
{ userAgent: "*", allow: "/" },
{ userAgent: "Googlebot", disallow: "/private" },
],
},
};
Finally, run the following command to generate the sitemap:
npx next-sitemap
This will create a sitemap.xml file in the public directory of your Next.js app.
58 How do you handle CORS in Next.js API routes? Medium
By setting appropriate headers in the API route response.
export default function handler(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.status(200).json({ message: "CORS enabled" });
}
59 How do you manage cookies in Next.js? Medium
By using the cookie package or next-cookies to read and write cookies in API routes or server-side functions.
import Cookies from "cookies";
export default function handler(req, res) {
const cookies = new Cookies(req, res);
cookies.set("token", "value", { httpOnly: true });
res.status(200).json({ message: "Cookie set" });
}
60 What is the purpose of next/dynamic? Medium
For dynamic importing of components with support for SSR.
import dynamic from "next/dynamic";
// Client-side only component
const DynamicComponentWithNoSSR = dynamic(
() => import("../components/hello"),
{
ssr: false,
}
);
function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<Footer />
</div>
);
}
export default Home;
61 How to consider security in Next.js app router? Medium
To consider security in Next.js app router, you can follow these best practices:
- Use HTTPS for all requests to ensure data is encrypted in transit.
- Implement authentication and authorization to protect sensitive routes.
- Sanitize user input to prevent XSS attacks.
- Use environment variables to store sensitive information like API keys.
- Regularly update dependencies to patch known vulnerabilities.
- Implement Content Security Policy (CSP) headers to mitigate XSS attacks.
- Use secure cookies with the
HttpOnlyandSecureflags.
62 What is the useTranslation hook in Next.js? Medium
useTranslation is a custom hook provided by the next-i18next and react-i18next libraries for implementing internationalization (i18n) and multi-language translations in Next.js applications:
### How It Works:
- Translation strings are stored in JSON files per locale:
public/locales/
├── en/common.json --> { "welcome": "Welcome back, {{name}}!" }
└── es/common.json --> { "welcome": "¡Bienvenido de nuevo, {{name}}!" }
- Using the hook inside a component:
import { useTranslation } from 'next-i18next';
export function Header({ userName }: { userName: string }) {
const { t } = useTranslation('common');
return <h1>{t('welcome', { name: userName })}</h1>;
}
### In Modern App Router:
Modern Next.js 13+ App Router natively supports localized sub-path routing (e.g. app/[lang]/page.tsx) with dictionary loaders (getDictionary(lang)), reducing dependency on heavy client-side i18n libraries.
63 What is AMP in Next.js? Medium
AMP (Accelerated Mobile Pages) is an open-source HTML framework created by Google to build ultra-fast, lightweight web pages for mobile devices by strictly constraining JavaScript and external styling.
### AMP in Next.js:
Next.js provided built-in support for generating both AMP-first pages and hybrid AMP pages (serving AMP to mobile search bots and full React to desktop users).
### Modern Industry Context:
AMP support in Next.js is now largely considered legacy. Google Search no longer requires AMP for Top Stories placement, prioritizing Core Web Vitals (LCP, FID/INP, CLS) instead. Modern Next.js applications achieve superior performance without AMP limitations using Server Components, streaming, and edge caching.
64 How do you enable AMP in Next.js? Medium
In the Next.js Pages Router, AMP was enabled on a per-page basis by exporting an amp configuration object:
### 1. Hybrid AMP Page:
// pages/article.js
export const config = { amp: 'hybrid' };
import { useAmp } from 'next/amp';
export default function ArticlePage() {
const isAmp = useAmp();
return (
<div>
<h1>{isAmp ? 'Fast AMP Version' : 'Full Interactive Version'}</h1>
</div>
);
}
### 2. AMP-Only Page:
// pages/about.js
export const config = { amp: true };
export default function About() {
return <h1>Pure AMP Page</h1>;
}
*Note: AMP is not supported in the modern App Router (app/ directory).*
65 What is the difference between pages and components directories? Medium
In professional Next.js architecture, separating pages (or app) from components is fundamental to project organization:
| Aspect | pages/ (or app/) | components/ |
| :--- | :--- | :--- |
| Routing | Maps directly to public URLs | Never generates routes |
| Purpose | Defines route endpoints, page layouts, metadata | Houses reusable UI building blocks |
| Structure | Bound to URL hierarchy | Organized by feature (Button, Card, Navbar) |
| Data Fetching | Top-level entry point for route data fetching | Receives data via props or local hooks |
### Clean Architecture Example:
src/
├── app/
│ ├── page.tsx --> Home page route (/)
│ └── questions/
│ └── page.tsx --> Questions route (/questions)
└── components/
├── ui/
│ ├── Button.tsx --> Reusable button
│ └── Modal.tsx --> Reusable modal
└── questions/
└── QuestionCard.tsx --> Question display component
66 How do you handle static files in Next.js? Medium
By placing them in the public directory, which is served at the root URL.
public/
├── images/
│ └── logo.png
└── favicon.ico
You can access these files using /images/logo.png or /favicon.ico.
67 List some common performance optimization techniques in Next.js. Medium
- Use static generation (SSG) for pages that can be pre-rendered.
- Implement incremental static regeneration (ISR) for dynamic content.
- Use the next/image component for optimized images.
- Enable code splitting and tree shaking.
- Use dynamic imports for large components.
- Optimize CSS with CSS modules or styled-components.
- Leverage caching strategies for API routes.
68 Mention some common security practices in Next.js. Medium
- Use HTTPS for secure communication.
- Implement authentication and authorization.
- Sanitize user input to prevent XSS attacks.
- Use environment variables for sensitive data.
- Regularly update dependencies to patch vulnerabilities.
- Implement Content Security Policy (CSP) headers.
- Use secure cookies with
HttpOnlyandSecureflags.
69 Are there any limitations of Next.js? Medium
- Limited support for non-React libraries.
- Requires a Node.js server for server-side rendering.
- Some features may not be compatible with static site generation.
- Learning curve for developers new to React or Next.js.
70 Is Next.js suitable for large-scale applications? Medium
Yes, Next.js is suitable for large-scale applications due to its features like server-side rendering, static site generation, and API routes. It also supports code splitting, dynamic imports, and incremental static regeneration, which help in managing large codebases efficiently.
71 How Next.js are full stack framework? Medium
Next.js is considered a full-stack framework because it allows developers to build both the frontend and backend of web applications within a single codebase. It provides features like server-side rendering, static site generation, API routes, and database integration, enabling the development of complete web applications without needing separate frameworks for the frontend and backend.
72 Prevent API routes from being accessed by the client? Medium
To prevent API routes from being accessed by the client, you can implement authentication and authorization checks in your API route handlers. This ensures that only authenticated users can access the API endpoints.
export default function handler(req, res) {
const token = req.headers.authorization;
if (!token || !isValidToken(token)) {
return res.status(401).json({ error: "Unauthorized" });
}
// Handle the request
res.status(200).json({ message: "Success" });
}
73 JWT Token in Next.js? Medium
JSON Web Tokens (JWT) can be used in Next.js for authentication and authorization. You can create a JWT token upon user login and store it in a cookie or local storage. Then, you can verify the token in API routes or server-side functions to authenticate users.
import jwt from "jsonwebtoken";
// Create a JWT token
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
// Verify the JWT token
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ error: "Invalid token" });
}
// Proceed with authenticated user
});
74 How do you handle global styles in the App Router? Medium
By creating a globals.css file in the app directory and importing it in the _app.js file.
/* app/globals.css */
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
}
Then import it in your _app.js:
// app/_app.js
import "../globals.css";
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
75 How do you enable ISR (revalidation) in the App Router? Medium
In the App Router you can control revalidation when fetching data by passing the next option to fetch. For example, to revalidate every 10 seconds:
const res = await fetch("https://api.example.com/data", {
next: { revalidate: 10 },
});
const data = await res.json();
76 How should you expose environment variables to the client safely? Medium
Only expose non-sensitive variables by prefixing them with NEXT_PUBLIC_. Keep secrets (API keys, DB credentials) server-only in .env and access them from server-side code or API routes.
NEXT_PUBLIC_API_BASE=https://api.example.com
SECRET_API_KEY=supersecret
77 What is the Pages Router in Next.js? Medium
The Pages Router is a file-based routing system in Next.js that automatically creates routes based on the file structure inside the pages directory.
78 What is catch all segment in Next.js? Medium
A catch-all segment allows you to match multiple segments in a dynamic route. It is defined using [[...param]] syntax.
This allows you to create routes that can match multiple segments, such as /docs/nextjs, /docs/react, etc.
// pages/docs/[[...slug]].js
export default function Docs({ params }) {
return <div>Docs: {params.slug.join("/")}</div>;
}
79 What is the \_app.js file in Next.js? Medium
In the Next.js Pages Router, pages/_app.js (or _app.tsx) is the top-level root component that wraps every single page in the application during rendering:
### Key Responsibilities of _app.js:
- Persisting Layouts & Navigation: Keeps persistent navigation headers, footers, and sidebars from re-rendering across page changes.
- Global CSS Imports: The only file in Pages Router permitted to import global stylesheets (
import '../styles/globals.css'). - Global State & Context Providers: Wrapping the app with ThemeProvider, Redux Provider, React Query ClientProvider, or AuthProvider.
- Custom Error Handling & Analytics: Tracking route change pageviews with Google Analytics.
### Example Implementation:
// pages/_app.tsx
import type { AppProps } from 'next/app';
import '../styles/globals.css';
import { AuthProvider } from '@/context/AuthContext';
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
);
}
80 What is the \_document.js file in Next.js? Medium
In the Next.js Pages Router, pages/_document.js (or _document.tsx) allows developers to augment the server-rendered HTML document skeleton (<html>, <head>, <body>).
### Key Characteristics:
- Renders only on the server during the initial HTML generation; it is never executed on the client side.
- Event handlers (such as
onClick) do not work inside_document.js.
### Typical Use Cases:
- Custom HTML lang attributes:
<Html lang="en"> - Custom font link tags and favicons
- Third-party tracking scripts injected into
<Head> - CSS-in-JS SSR styling injections (such as Styled Components or Emotion style collection)
### Standard Template:
// pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html lang="en">
<Head />
<body className="bg-gray-50 antialiased">
<Main />
<NextScript />
</body>
</Html>
);
}
81 What is the difference between \_app.js and \_document.js? Medium
While both are root-level files in the Next.js Pages Router, they operate at fundamentally different layers:
| Dimension | _app.js | _document.js |
| :--- | :--- | :--- |
| Execution | Runs on both Server and Client | Runs only on Server |
| Scope | Wraps React component page hierarchy | Wraps initial HTML shell (<html>, <body>) |
| Interactivity | Supports React hooks, state, event listeners | Zero client interactivity (no hooks, no event handlers) |
| CSS | Can import global CSS files | Cannot import stylesheets directly |
| Purpose | Shared layouts, context providers, state | Document metadata, language tag, custom scripts |
### Modern App Router Note:
In the modern App Router (app/ directory), both files are replaced by a single, unified app/layout.tsx root layout file.
82 What is the \_error.js file in Next.js? Medium
In the Next.js Pages Router, pages/_error.js (or _error.tsx) is a fallback error page rendered whenever an unhandled HTTP exception (such as a 500 internal server error or unhandled runtime rejection) occurs:
### Key Functionality:
- Captures status codes from server responses (
res.statusCode) or client errors (err.statusCode). - Overrides Next.js's default error page with custom branded styling.
### Example Implementation:
// pages/_error.tsx
import { NextPageContext } from 'next';
function Error({ statusCode }: { statusCode?: number }) {
return (
<div className="error-container">
<h1>{statusCode ? `An error ${statusCode} occurred on server` : 'An error occurred on client'}</h1>
</div>
);
}
Error.getInitialProps = ({ res, err }: NextPageContext) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
83 How do you fetch data in a Next.js page? Medium
Using getStaticProps or getServerSideProps in server side.
// 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;
}
jsx
// 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>
);
}
84 What is getStaticProps? Medium
A function that runs at build time to fetch data for a page.
export async function getStaticProps(context) {
const res = await fetch(`https://...`);
const data = await res.json();
if (!data) {
return {
notFound: true,
};
}
return {
props: { data }, // will be passed to the page component as props
};
}
85 What is getServerSideProps? Medium
A function that runs on each request to fetch data for a page.
export async function getServerSideProps(context) {
const res = await fetch(`https://...`);
const data = await res.json();
if (!data) {
return {
notFound: true,
};
}
return {
props: { data }, // will be passed to the page component as props
};
}
86 What is the difference between getStaticProps and getServerSideProps? Medium
In the Next.js Pages Router, getStaticProps and getServerSideProps dictate data fetching and page caching behavior:
### 1. getStaticProps (Static Site Generation):
- Executes only at build time on the server (or incrementally via ISR
revalidate). - Produces static HTML and JSON files deployed to CDN edge caches.
- When to use: Content that is identical for all users (e.g. blog posts, documentation, marketing landing pages, technical interview guides).
export async function getStaticProps() {
const data = await fetchQuestions();
return { props: { data }, revalidate: 3600 }; // ISR every 1 hour
}
### 2. getServerSideProps (Server-Side Rendering):
- Executes on the server on every incoming HTTP request.
- Has access to the incoming request object (
req), cookies, and query strings. - When to use: Pages displaying sensitive user-specific data, real-time live feeds, or requiring authentication session validation before rendering.
export async function getServerSideProps(context) {
const session = await getSession(context.req);
if (!session) return { redirect: { destination: '/login' } };
return { props: { user: session.user } };
}
87 What is getStaticPaths? Medium
A function that specifies dynamic routes to pre-render based on data.
export async function getStaticPaths() {
const res = await fetch("https://.../posts");
const posts = await res.json();
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}));
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false };
}
88 What is fallback in getStaticPaths? Medium
Determines how to handle missing paths, with true, false, or 'blocking'.
export async function getStaticPaths() {
const paths = await getAllPostIds();
return {
paths,
fallback: true, // this will enable fallback for all paths which are not generated at build time
};
}
jsx
export async function getStaticPaths() {
const paths = await getAllPostIds();
return {
paths,
fallback: false, // this will return 404 for all paths which are not generated at build time
};
}
jsx
export async function getStaticPaths() {
const paths = await getAllPostIds();
return {
paths,
fallback: "blocking", // this will return a static page for all paths which are not generated at build time
};
}
89 How do you handle API routes in the Next.js Pages Router? Medium
By creating files in the pages/api directory, which will be treated as API endpoints.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ name: "John Doe" });
}
You can access this API route at /api/hello.
90 How do you handle custom error pages in Next.js? Medium
By creating a _error.js file in the pages directory.
// pages/_error.js
export default function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred on server`
: "An error occurred on client"}
</p>
);
}
91 Are there any limitations of the Pages Router? Medium
Yes, the Pages Router has some limitations compared to the App Router, such as:
- Limited support for nested routes and layouts.
- Less flexibility in handling server components.
- No support for React Server Components.
92 How do you handle authentication in Next.js with the Pages Router? Medium
By using libraries like next-auth or implementing custom authentication logic in API routes.
// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
// Add more configuration options as needed
});
93 How do you handle form submissions in Next.js with the Pages Router? Medium
By using client-side form handling or API routes for server-side handling.
// pages/contact.js
export default function Contact() {
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const response = await fetch("/api/contact", {
method: "POST",
body: formData,
});
if (response.ok) {
alert("Form submitted successfully!");
} else {
alert("Error submitting form.");
}
};
return (
<form onSubmit={handleSubmit}>
<input name="name" type="text" placeholder="Name" required />
<input name="email" type="email" placeholder="Email" required />
<button type="submit">Submit</button>
</form>
);
}
94 Are there any performance optimizations available in the Pages Router? Medium
Yes, you can use features like static generation (SSG), server-side rendering (SSR), and incremental static regeneration (ISR) to optimize performance in the Pages Router.
- Static Generation (SSG): Pre-render pages at build time.
- Server-Side Rendering (SSR): Render pages on each request.
- Incremental Static Regeneration (ISR): Update static pages after the build.
95 How do you handle internationalization in Next.js with the Pages Router? Medium
By using the next-i18next library or the built-in internationalization features in Next.js.
// next.config.js
module.exports = {
i18n: {
locales: ["en", "fr"],
defaultLocale: "en",
},
};
Then, you can use the useTranslation hook from next-i18next to handle translations in your components.
import { useTranslation } from "next-i18next";
export default function Home() {
const { t } = useTranslation("common");
return <h1>{t("welcome")}</h1>;
}
96 How do you handle SEO in Next.js with the Pages Router? Medium
By using the next/head component to manage meta tags and other SEO-related elements.
import Head from "next/head";
export default function Home() {
return (
<>
<Head>
<title>My Next.js App</title>
<meta
name="description"
content="A description of my Next.js app"
/>
</Head>
<h1>Welcome to My Next.js App</h1>
</>
);
}
97 How do you handle static assets in Next.js with the Pages Router? Medium
By placing static assets in the public directory, which is served at the root URL.
public/
├── images/
│ └── logo.png
└── favicon.ico
You can access these files using /images/logo.png or /favicon.ico.
98 How cache works in Next.js with the Pages Router? Medium
Next.js uses a built-in caching mechanism for static assets and API routes. You can also implement custom caching strategies using HTTP headers or libraries like next-cache.
- Static Assets: Cached by default with a long cache lifetime.
- API Routes: Can be cached using HTTP headers like
Cache-Control.
export default function handler(req, res) {
res.setHeader("Cache-Control", "public, max-age=3600, immutable");
res.status(200).json({ message: "Cached response" });
}
99 Cache revalidation in Next.js with the Pages Router? Medium
Cache revalidation can be handled using the revalidate option in getStaticProps or by setting appropriate HTTP headers in API routes.
- Using
revalidate: Automatically revalidates static pages after a specified time.
export async function getStaticProps() {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
return {
props: { data },
revalidate: 10, // Revalidate every 10 seconds
};
}
- Using HTTP Headers: Set cache control headers in API routes.
export default function handler(req, res) {
res.setHeader("Cache-Control", "s-maxage=10, stale-while-revalidate");
res.status(200).json({ message: "Revalidated response" });
}
100 Optimizing images in Next.js with the Pages Router? Medium
By using the next/image component, which automatically optimizes images for performance.
import Image from "next/image";
export default function Home() {
return (
<div>
<h1>My Next.js App</h1>
<Image
src="/images/logo.png"
alt="Logo"
width={500}
height={300}
quality={75}
/>
</div>
);
}
The next/image component provides features like lazy loading, responsive images, and automatic format selection.
101 When to choose Pages Router over App Router in Next.js? Medium
You might choose the Pages Router over the App Router in the following scenarios:
- When you need a simple file-based routing system without complex nested routes.
- When you prefer the traditional Next.js routing approach.
- When your application does not require advanced features like server components or layouts.
The Pages Router is suitable for smaller applications or when you want to leverage existing knowledge of Next.js routing.
102 When to choose App Router over Pages Router in Next.js? Medium
You might choose the App Router over the Pages Router in the following scenarios:
- When you need advanced routing capabilities, such as nested routes and layouts.
- When you want to leverage React Server Components for better performance and flexibility.
- When your application requires more complex data fetching strategies.
The App Router is suitable for larger applications or when you want to take advantage of the latest features in Next.js 13.
103 What is the App Router in Next.js? Medium
The App Router is a new routing system introduced in Next.js 13 that allows for more flexible and powerful routing capabilities, including nested routes, layouts, and server components.
104 How do you handle form submissions in Next.js? Medium
Form handling in Next.js has evolved into two primary architectures:
### 1. Modern Approach: Server Actions (App Router - Recommended):
Server Actions allow forms to execute server-side database mutations directly without manually configuring API routes:
// app/contact/page.tsx
export default function ContactForm() {
async function handleSubmit(formData: FormData) {
'use server';
const email = formData.get('email');
const message = formData.get('message');
await db.inquiry.create({ data: { email, message } });
}
return (
<form action={handleSubmit}>
<input type="email" name="email" required />
<textarea name="message" required />
<button type="submit">Send Message</button>
</form>
);
}
### 2. Traditional Approach: Client Fetch to Route Handlers:
Manage local input state with useState or React Hook Form, submitting via fetch to /api/contact:
'use client';
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
await fetch('/api/contact', {
method: 'POST',
body: JSON.stringify(formData),
headers: { 'Content-Type': 'application/json' },
});
};
105 How do you implement authentication in Next.js? Medium
Authentication in Next.js applications is typically implemented using one of three industry-standard architectural patterns:
### 1. NextAuth.js / Auth.js (Industry Standard):
The most popular open-source authentication library specifically built for Next.js.
- Supports OAuth providers (Google, GitHub, Apple), credentials (email/password), and passwordless magic links.
- Handles encrypted JWT sessions and HTTP-only cookies automatically:
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import GithubProvider from 'next-auth/providers/github';
const handler = NextAuth({
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
],
});
export { handler as GET, handler as POST };
### 2. Managed Identity Providers (Clerk / Supabase / Auth0):
Drop-in SDKs providing pre-built user management components (<SignIn />, <UserButton />) and session tokens verified in Next.js Middleware.
### 3. Custom JWT & HTTP-Only Cookies:
Issue signed JWT tokens upon login, stored strictly in secure HTTP-only cookies (SameSite=Lax; HttpOnly; Secure) to defend against Cross-Site Scripting (XSS) attacks. Verify token validity within middleware.ts on protected route segments.
106 How to add authjs in Next.js app router? Medium
To add authjs in nextjs app router, you can use the next-auth package. First, install it:
npm install next-auth
Then, create a file named [...nextauth].js in the app/api/auth directory and configure your authentication providers.
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
// Add more configuration options as needed
callbacks: {
async session(session, user) {
// Add custom session properties here
return session;
},
},
pages: {
signIn: "/auth/signin", // Custom sign-in page
error: "/auth/error", // Error page
},
secret: process.env.NEXTAUTH_SECRET, // Required for JWT encryption
session: {
jwt: true, // Use JWT for session management
},
jwt: {
secret: process.env.NEXTAUTH_JWT_SECRET, // Required for JWT encryption
},
events: {
signIn: async (message) => {
// Custom logic after sign-in
console.log("User signed in:", message);
},
},
debug: process.env.NODE_ENV === "development", // Enable debug mode in development
theme: {
colorScheme: "light", // Change to "dark" for dark mode
brandColor: "#0000FF", // Custom brand color
logo: "/logo.png", // Custom logo URL
},
pages: {
signIn: "/auth/signin", // Custom sign-in page
signOut: "/auth/signout", // Custom sign-out page
error: "/auth/error", // Error page
verifyRequest: "/auth/verify-request", // Verification request page
newUser: null, // Will disable the new account creation screen
},
});
107 How do you handle authentication tokens in Next.js? Medium
By using cookies or local storage to store authentication tokens.
// Example of setting a token in a cookie
import Cookies from "js-cookie";
function setToken(token) {
Cookies.set("authToken", token, { expires: 7 }); // Expires in 7 days
}
function getToken() {
return Cookies.get("authToken");
}
108 How to add credentials in Next.js app router? Medium
To add credentials in Next.js app router, you can use the next-auth package with the Credentials provider. First, install it:
npm install next-auth
Then, create a file named [...nextauth].js in the app/api/auth directory and configure your credentials provider.
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
// Add your own logic to validate credentials here
const user = { id: 1, name: "John Doe" }; // Example user
if (
credentials.username === "admin" &&
credentials.password === "password"
) {
return user; // Return user object if credentials are valid
} else {
return null; // Return null if credentials are invalid
}
},
}),
],
pages: {
signIn: "/auth/signin", // Custom sign-in page
},
callbacks: {
async session(session, user) {
session.user = user; // Add user object to session
return session;
},
},
secret: process.env.NEXTAUTH_SECRET, // Required for JWT encryption
session: {
jwt: true, // Use JWT for session management
},
jwt: {
secret: process.env.NEXTAUTH_JWT_SECRET, // Required for JWT encryption
},
});
109 What is use server in Next.js? Medium
The use server directive is used to indicate that a function should be executed on the server side. It allows you to write server-side logic in a component or function that can be called from the client side.
"use server";
export async function myServerFunction() {
// Server-side logic here
return "Hello from the server!";
}
110 Difference between using & not using use server in Next.js? Medium
Using use server: The function is executed on the server side, allowing access to server-side resources and APIs. It can be used to perform operations that require server-side logic, such as database queries or API calls.
Not using use server: The function is executed on the client side, meaning it cannot access server-side resources directly. It can only perform operations that are available in the client environment, such as manipulating the DOM or making client-side API calls.
- Example with
use server:
"use server";
export async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
}
- Example without
use server:
export async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
}
- Example with
use serverIn Component:
import { fetchData } from "./path/to/your/file";
export default function MyComponent() {
const data = await fetchData(); // This will run on the server side
return <div>{data}</div>;
}
- Example without
use serverIn Component:
import { fetchData } from "./path/to/your/file";
export default function MyComponent() {
const data = fetchData(); // This will run on the client side
return <div>{data}</div>;
}
111 How do you handle Route Handlers in the Next.js App Router? Medium
By creating files in the app/api directory, where each file corresponds to an API endpoint.
// app/api/hello/route.js
export async function GET(request) {
return new Response("Hello, World!");
}
112 What is form action in Next.js? Medium
The formAction is a special attribute used in Next.js to define the action URL for a form submission. It allows you to specify a server-side function that will handle the form submission.
// app/form-example/page.js
"use server";
export async function handleSubmit(formData) {
const name = formData.get("name");
console.log("Form submitted with name:", name);
return { success: true };
}
export default function FormExample() {
return (
<form action={handleSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
);
}
In this example, when the form is submitted, the handleSubmit function will be called on the server side with the form data.
113 How do you handle file uploads in Next.js? Medium
By using the formData API in a server action to handle file uploads.
// app/upload/page.js
"use server";
export async function handleUpload(formData) {
const file = formData.get("file");
// Process the file (e.g., save it to a storage service)
console.log("File uploaded:", file.name);
return { success: true };
}
export default function UploadPage() {
return (
<form action={handleUpload} encType="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
);
}
114 Mention some common use cases for the App Router in Next.js. Medium
- Creating nested routes with layouts.
- Implementing server-side rendering for dynamic content.
- Handling API routes for backend functionality.
- Managing authentication and authorization flows.
- Building complex applications with shared layouts and components.
115 One of the main differences between the App Router and Pages Router in Next.js? Medium
The App Router allows for nested routes, layouts, and server components, while the Pages Router uses a flat file structure for routing and does not support nested routes or layouts.
116 What is the use of the `use client` directive in Next.js? Medium
The use client directive is used to indicate that a component should be rendered on the client side. It allows you to write client-side logic in a component that can be executed in the browser.
"use client";
export default function ClientComponent() {
return <div>This component is rendered on the client side.</div>;
}
117 Is it possible to use both App Router and Pages Router in the same Next.js project? Medium
Yes, it is possible to use both App Router and Pages Router in the same Next.js project. You can have the app directory for the App Router and the pages directory for the Pages Router, allowing you to take advantage of both routing systems.
118 Are there any limitations of the App Router in Next.js? Medium
Yes, some limitations of the App Router include:
- It is only available in Next.js 13 and later versions.
- It may not support all features available in the Pages Router.
- Some third-party libraries may not be compatible with the App Router.
- Many features from the Pages Router, such as
getStaticPropsandgetServerSideProps, are not available in the App Router. - The App Router is still evolving, and some features may change or be added in future releases.
119 The difference between `use server` and `use client` in Next.js? Medium
use server: Indicates that the function should be executed on the server side. It allows you to write server-side logic that can be called from the client side.
use client: Indicates that the component should be rendered on the client side. It allows you to write client-side logic that can be executed in the browser.
// Example of use server
"use server";
export async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
}
// Example of use client
("use client");
export default function ClientComponent() {
return <div>This component is rendered on the client side.</div>;
}
120 Understand the concept of server actions in Next.js. Medium
Server actions in Next.js allow you to define functions that can be executed on the server side when a form is submitted or an action is triggered. These functions can handle data processing, database interactions, or any server-side logic.
// app/actions/submitForm.js
"use server";
export async function submitForm(formData) {
const name = formData.get("name");
console.log("Form submitted with name:", name);
return { success: true };
}
You can then use this action in a form:
// app/form/page.js
import { submitForm } from "../actions/submitForm";
export default function FormPage() {
return (
<form action={submitForm}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
);
}
121 Whats are the benifit of using server actions in Next.js? Medium
- Performance: Server actions allow you to offload heavy computations or data processing to the server, reducing the load on the client.
- Security: Sensitive operations can be performed on the server, preventing exposure of sensitive data or logic to the client.
- Simplified Data Fetching: You can fetch data directly in server actions without needing to manage client-side state or effects.
- Reduced Client Bundle Size: By moving logic to the server, you can reduce the amount of JavaScript sent to the client, improving load times.
122 What's are the problem of using server actions in Next.js? Medium
- Latency: Server actions can introduce latency since they require a round trip to the server, which may not be ideal for real-time interactions.
- Complexity: Managing server actions can add complexity to your application, especially if you have many actions or need to handle different states.
- Limited Client-Side Interactivity: Since server actions are executed on the server, they may not provide the same level of interactivity as client-side functions.
- Debugging Challenges: Debugging server actions can be more challenging compared to client-side code, as you may not have access to browser developer tools.
123 Alternative options instead of server actions in Next.js? Medium
- API Routes: You can create API routes to handle server-side logic and data fetching, which can be called from the client side.
- Client-Side Fetching: Use client-side data fetching methods like
useEffector libraries like SWR or React Query to manage data on the client side. - Static Site Generation (SSG): Use SSG for pages that can be pre-rendered at build time, reducing the need for server actions.
- Server-Side Rendering (SSR): Use SSR for dynamic pages that require server-side data fetching on each request.
124 Alternative solutions example of not using server actions in Next.js? Medium
Instead of using server actions, you can use API routes to handle form submissions or data processing. Here's an example:
// app/api/submitForm/route.js
export async function POST(request) {
const formData = await request.formData();
const name = formData.get("name");
console.log("Form submitted with name:", name);
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
You can then call this API route from a client-side component:
// app/form/page.js
export default function FormPage() {
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const response = await fetch("/api/submitForm", {
method: "POST",
body: formData,
});
const result = await response.json();
console.log(result);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
);
}
125 JWT Token in Next.js App Router? Medium
JSON Web Tokens (JWT) can be used in the Next.js App Router for authentication and authorization. You can create a JWT token upon user login and store it in a cookie or local storage. Then, you can verify the token in API routes or server-side functions to authenticate users.
import jwt from "jsonwebtoken";
// Create a JWT token
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
// Verify the JWT token
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ error: "Invalid token" });
}
// Proceed with authenticated user
});
Using it on application:
// app/api/auth/route.js
import { NextResponse } from "next/server";
import jwt from "jsonwebtoken";
export async function POST(request) {
const { token } = await request.json();
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
return NextResponse.json({ userId: decoded.userId });
} catch (error) {
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
}
}
You can also use JWT tokens for protecting API routes:
// app/api/protected/route.js
import { NextResponse } from "next/server";
import jwt from "jsonwebtoken";
export async function GET(request) {
const token = request.cookies.get("authToken");
if (!token) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Handle the request for authorized users
return NextResponse.json({
message: "Protected data",
userId: decoded.userId,
});
} catch (error) {
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
}
}
126 Context of JWT Token in Next.js App Router? Medium
The context of using JWT tokens in the Next.js App Router is primarily for authentication and authorization purposes. JWT tokens allow you to securely transmit user information between the client and server, enabling you to verify user identity and permissions without needing to store session data on the server.
This approach is particularly useful for stateless applications where you want to maintain user sessions without relying on server-side session storage.
127 Is App Router better than Pages Router in Next.js? Medium
The App Router offers more flexibility and features compared to the Pages Router, such as nested routes, layouts, and server components. It is designed for building complex applications with shared layouts and components.
However, the choice between App Router and Pages Router depends on your specific use case. If you need simple routing without nested routes or layouts, the Pages Router may be sufficient.
128 How to handle global state management in Next.js with the App Router? Medium
You can handle global state management in Next.js with the App Router using libraries like Redux, Zustand, or React Context API. These libraries allow you to create a global store that can be accessed from any component in your application.
- Using React Context API:
// app/context/GlobalState.js
import { createContext, useContext, useState } from "react";
const GlobalStateContext = createContext();
export function GlobalStateProvider({ children }) {
const [state, setState] = useState({ user: null });
return (
<GlobalStateContext.Provider value={{ state, setState }}>
{children}
</GlobalStateContext.Provider>
);
}
export function useGlobalState() {
return useContext(GlobalStateContext);
}
Then wrap your application with the GlobalStateProvider:
// app/layout.js
import { GlobalStateProvider } from "./context/GlobalState";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<GlobalStateProvider>{children}</GlobalStateProvider>
</body>
</html>
);
}
Now you can access the global state in any component using the useGlobalState hook.
// app/page.js
import { useGlobalState } from "./context/GlobalState";
export default function HomePage() {
const { state, setState } = useGlobalState();
return (
<div>
<h1>Welcome, {state.user ? state.user.name : "Guest"}</h1>
<button onClick={() => setState({ user: { name: "John Doe" } })}>
Log In
</button>
</div>
);
}
129 What is the fetch API in Next.js App Router? Medium
In the Next.js App Router, you can use the fetch API to make HTTP requests to external APIs or your own API routes. The fetch function is available globally in both server and client components.
- Example of using fetch in a server component:
// app/api/data/route.js
export async function GET() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" },
});
}
- Example of using fetch in a client component:
// app/page.js
import { useEffect, useState } from "react";
export default function HomePage() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const response = await fetch("/api/data");
const result = await response.json();
setData(result);
}
fetchData();
}, []);
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
130 How do you create route groups in the App Router? Medium
Route groups allow you to organize routes without affecting the URL structure. You create them by wrapping folder names in parentheses ().
app/
├── (marketing)/
│ ├── about/
│ │ └── page.js // /about
│ └── contact/
│ └── page.js // /contact
├── (shop)/
│ ├── products/
│ │ └── page.js // /products
│ └── cart/
│ └── page.js // /cart
└── layout.js // Shared layout
Route groups are useful for organizing code, creating different layouts for different sections, or conditionally including layouts.
131 What is the loading.js file in App Router? Medium
The loading.js file creates loading UI that shows instantly while route segments are loading. It automatically wraps the page and its children in a React Suspense boundary.
// app/dashboard/loading.js
export default function Loading() {
return (
<div className="loading">
<p>Loading dashboard...</p>
<div className="spinner"></div>
</div>
);
}
app/
├── dashboard/
│ ├── loading.js // Loading UI for dashboard
│ ├── page.js
│ └── settings/
│ ├── loading.js // Loading UI for settings
│ └── page.js
The loading UI will be shown immediately on navigation and can be nested for granular loading states.
132 How do you handle not-found pages in App Router? Medium
You can create custom not-found pages using the not-found.js file. This file defines UI to render when the notFound() function is thrown within a route segment.
// app/not-found.js
import Link from "next/link";
export default function NotFound() {
return (
<div>
<h2>Not Found</h2>
<p>Could not find requested resource</p>
<Link href="/">Return Home</Link>
</div>
);
}
You can also trigger the not-found page programmatically:
// app/page.js
import { notFound } from "next/navigation";
export default function Page({ params }) {
const post = getPost(params.id);
if (!post) {
notFound();
}
return <div>{post.title}</div>;
}
133 What is the template.js file in App Router? Medium
The template.js file is similar to layout.js but creates a new instance for each of its children on navigation. This means state is not preserved and effects are re-synchronized.
// app/template.js
export default function Template({ children }) {
return <div className="template-wrapper">{children}</div>;
}
Key differences from layout:
- Layout: State is preserved, DOM elements are not re-created
- Template: New instance on navigation, DOM elements are re-created
Templates are useful when you need:
- CSS/JS animations on route changes
- Features that rely on
useEffectanduseState - To change the default browser behavior
134 How do you implement nested layouts in App Router? Medium
Nested layouts are implemented by creating layout.js files in different route segments. Layouts are nested automatically based on the folder structure.
app/
├── layout.js // Root layout
├── page.js // Home page
└── dashboard/
├── layout.js // Dashboard layout
├── page.js // Dashboard page
└── settings/
├── layout.js // Settings layout
└── page.js // Settings page
jsx
// app/layout.js (Root Layout)
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<nav>Global Navigation</nav>
{children}
</body>
</html>
);
}
// app/dashboard/layout.js
export default function DashboardLayout({ children }) {
return (
<div className="dashboard">
<aside>Dashboard Sidebar</aside>
<main>{children}</main>
</div>
);
}
When visiting /dashboard/settings, all three layouts (root, dashboard, settings) will be rendered in a nested structure.
135 What are route handlers vs API routes in App Router? Medium
In the App Router, API routes are now called "Route Handlers" and use the route.js file convention instead of the pages-based approach.
Pages Router (API Routes):
pages/api/users.js
App Router (Route Handlers):
app/api/users/route.js
jsx
// app/api/users/route.js
export async function GET(request) {
const users = await getUsers();
return Response.json(users);
}
export async function POST(request) {
const data = await request.json();
const user = await createUser(data);
return Response.json(user, { status: 201 });
}
export async function PUT(request) {
const data = await request.json();
const user = await updateUser(data);
return Response.json(user);
}
export async function DELETE(request) {
await deleteUser(request.nextUrl.searchParams.get("id"));
return new Response(null, { status: 204 });
}
Route handlers support all HTTP methods and provide better TypeScript support and Web APIs compatibility.
136 What is React Server Components (RSC) in App Router? Medium
React Server Components (RSC) are a new React feature that allows components to be rendered on the server. In the App Router, components are Server Components by default.
Server Components (default):
// app/page.js - This is a Server Component
async function ServerComponent() {
const data = await fetch("https://api.example.com/data");
const result = await data.json();
return (
<div>
<h1>Server Rendered Data</h1>
<p>{result.message}</p>
</div>
);
}
Client Components (opt-in with "use client"):
// app/components/ClientComponent.js
"use client";
import { useState } from "react";
export default function ClientComponent() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
);
}
Benefits of Server Components:
- Direct access to server-side resources (databases, file system)
- No JavaScript bundle sent to client
- Improved performance and SEO
- Automatic code splitting
When to use Client Components:
- Interactive features (event handlers, state)
- Browser-only APIs (localStorage, geolocation)
- React hooks (useState, useEffect)
137 How do you handle error boundaries in App Router? Medium
You can create error boundaries using the error.js file in a route segment. This file defines UI to render when an error is thrown within that segment.
// app/error.js
import Link from "next/link";
export default function Error({ error, reset }) {
return (
<div>
<h2>Something went wrong!</h2>
<p>{error.message}</p>
<button onClick={reset}>Try Again</button>
<Link href="/">Return Home</Link>
</div>
);
}
You can also throw errors programmatically:
// app/page.js
export default function Page() {
throw new Error("An unexpected error occurred!");
return <div>This will not be rendered.</div>;
}
The error boundary will catch the error and display the custom error UI defined in error.js.
138 How do you differentiate between server and client components in Next.js? Medium
In Next.js, components are Server Components by default. To differentiate and create Client Components, you need to add the "use client" directive at the top of the component file.
- Server Components: These run on the server and can access server-side resources like databases and file systems. They do not include any client-side JavaScript in the bundle.
// app/page.js - This is a Server Component
async function ServerComponent() {
const data = await fetch("https://api.example.com/data");
const result = await data.json();
return (
<div>
<h1>Server Rendered Data</h1>
<p>{result.message}</p>
</div>
);
}
- Client Components: These run on the client side and can use React hooks, manage state, and handle user interactions. They must include the
"use client"directive.
// app/components/ClientComponent.js
"use client";
import { useState } from "react";
export default function ClientComponent() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
);
}
Use Server Components for static content and data fetching, and Client Components for interactivity and state management.
139 How do you handle internationalization (i18n) in Next.js with the App Router? Medium
Next.js provides built-in support for internationalization (i18n) in the App Router. You can configure i18n settings in the next.config.js file.
// next.config.js
module.exports = {
i18n: {
locales: ["en", "fr", "de"],
defaultLocale: "en",
},
};
You can then create localized content by using dynamic route segments for different languages.
app/
├── [locale]/
│ ├── page.js // Localized home page
│ └── about/
│ └── page.js // Localized about page
jsx
// app/[locale]/page.js
import { useRouter } from "next/router";
export default function HomePage() {
const { locale } = useRouter();
return <div>Welcome to the {locale} version of the site!</div>;
}
You can also use libraries like next-translate or react-i18next for more advanced i18n features.
140 What is use server, why and when to use it in Next.js? Medium
The "use server" directive in Next.js is used to indicate that a function should be executed on the server side. It allows you to write server-side logic that can be called from the client side, such as handling form submissions or processing data.
You should use "use server" when you need to perform operations that require server-side capabilities, such as:
- Accessing databases or file systems
- Performing secure operations that should not be exposed to the client
- Handling form submissions and processing data on the server
Example usage:
// app/form-example/page.js
"use server";
export async function handleSubmit(formData) {
const name = formData.get("name");
console.log("Form submitted with name:", name);
return { success: true };
}
export default function FormExample() {
return (
<form action={handleSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
);
}
In this example, the handleSubmit function is marked with "use server", indicating that it will run on the server when the form is submitted.
141 What are the best practices of Next.js API routes? Medium
- Use proper HTTP methods (GET, POST, PUT, DELETE) for different operations.
- Validate and sanitize input data to prevent security vulnerabilities.
- Handle errors gracefully and return appropriate HTTP status codes.
- Use middleware for common tasks like authentication and logging.
- Keep API routes modular and organized in separate files or folders.
- Optimize performance by caching responses when appropriate.
- Document your API endpoints for easier consumption by other developers.
142 How to use proper HTTP methods in Next.js API routes? Medium
In Next.js API routes, you can define different functions for each HTTP method (GET, POST, PUT, DELETE) within the same route file. This allows you to handle different types of requests appropriately.
Example:
// app/api/users/route.js
export async function GET(request) {
const users = await getUsers();
return new Response(JSON.stringify(users), {
headers: { "Content-Type": "application/json" },
});
}
export async function POST(request) {
const data = await request.json();
const user = await createUser(data);
return new Response(JSON.stringify(user), {
status: 201,
headers: { "Content-Type": "application/json" },
});
}
export async function PUT(request) {
const data = await request.json();
const user = await updateUser(data);
return new Response(JSON.stringify(user), {
headers: { "Content-Type": "application/json" },
});
}
export async function DELETE(request) {
const { searchParams } = new URL(request.url);
const userId = searchParams.get("id");
await deleteUser(userId);
return new Response(null, { status: 204 });
}
In this example, each function corresponds to a specific HTTP method, allowing you to handle requests accordingly.
143 How to validate and sanitize input data in Next.js API routes? Medium
To validate and sanitize input data in Next.js API routes, you can use libraries like Joi, Yup, or validator.js. These libraries help ensure that the data received from clients meets the expected format and is safe to use.
Example using Joi:
// app/api/users/route.js
import Joi from "joi";
const userSchema = Joi.object({
name: Joi.string().min(3).max(30).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(0).optional(),
});
export async function POST(request) {
const data = await request.json();
// Validate input data
const { error, value } = userSchema.validate(data);
if (error) {
return new Response(
JSON.stringify({ error: error.details[0].message }),
{
status: 400,
headers: { "Content-Type": "application/json" },
}
);
}
// Proceed with sanitized data
const user = await createUser(value);
return new Response(JSON.stringify(user), {
status: 201,
headers: { "Content-Type": "application/json" },
});
}
In this example, the userSchema defines the expected structure of the input data. The POST function validates the incoming data against this schema and returns an error response if validation fails.
144 How to handle errors in Next.js API routes? Medium
To handle errors in Next.js API routes, you can use try-catch blocks to catch exceptions and return appropriate HTTP status codes and error messages. This ensures that clients receive meaningful feedback when something goes wrong.
Example:
// app/api/users/route.js
export async function GET(request) {
try {
const users = await getUsers();
return new Response(JSON.stringify(users), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error fetching users:", error);
return new Response(
JSON.stringify({ error: "Failed to fetch users" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
}
export async function POST(request) {
try {
const data = await request.json();
const user = await createUser(data);
return new Response(JSON.stringify(user), {
status: 201,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error creating user:", error);
return new Response(
JSON.stringify({ error: "Failed to create user" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
}
In this example, both the GET and POST functions include try-catch blocks to handle potential errors. If an error occurs, a 500 Internal Server Error response is returned with a relevant error message.
145 How to keep Next.js API routes modular and organized? Medium
To keep Next.js API routes modular and organized, you can structure your API routes in a way that groups related functionality together. Here are some best practices:
- Use Folders: Create folders for different resources or functionalities. Each folder can contain route files for that specific resource.
app/
├── api/
│ ├── users/
│ │ ├── route.js // Handles user-related routes
│ │ └── auth.js // Authentication logic
│ ├── products/
│ │ └── route.js // Handles product-related routes
│ └── orders/
│ └── route.js // Handles order-related routes
- Separate Logic: Keep business logic separate from route handlers. You can create utility functions or services that handle data fetching, processing, and other operations.
// app/api/users/service.js
export async function getUsers() {
// Fetch users from database
}
export async function createUser(data) {
// Create a new user in the database
}
- Use Middleware: Implement middleware for common tasks like authentication, logging, or validation to avoid code duplication across multiple routes.
- Consistent Naming: Use consistent naming conventions for your route files and functions to make it easier to understand their purpose.
- Documentation: Document your API routes and their expected inputs/outputs to help other developers understand how to use them.
By following these practices, you can maintain a clean and organized codebase for your Next.js API routes.
146 RTK Query with Next.js App Router? Medium
RTK Query is a powerful data fetching and caching tool built on top of Redux Toolkit. You can use RTK Query in a Next.js App Router application to manage server state and interact with APIs efficiently.
Here's how to set up RTK Query in a Next.js App Router project:
- Install Redux Toolkit and RTK Query:
npm install @reduxjs/toolkit react-redux
- Create an API slice:
// app/store/apiSlice.js
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const apiSlice = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({ baseUrl: "/api" }),
endpoints: (builder) => ({
getUsers: builder.query({
query: () => "users",
}),
}),
});
export const { useGetUsersQuery } = apiSlice;
- Set up the Redux store:
// app/store/store.js
import { configureStore } from "@reduxjs/toolkit";
import { apiSlice } from "./apiSlice";
export const store = configureStore({
reducer: {
[apiSlice.reducerPath]: apiSlice.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
});
- Wrap your application with the Redux Provider:
// app/layout.js
import { Provider } from "react-redux";
import { store } from "./store/store";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<Provider store={store}>{children}</Provider>
</body>
</html>
);
}
- Use RTK Query hooks in your components:
// app/page.js
import { useGetUsersQuery } from "./store/apiSlice";
export default function HomePage() {
const { data: users, error, isLoading } = useGetUsersQuery();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error loading users</div>;
return (
<div>
<h1>User List</h1>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
147 Redux Toolkit with Next.js App Router? Medium
Redux Toolkit (RTK) can be seamlessly integrated with Next.js App Router to manage global state in your application. Here's how to set up Redux Toolkit in a Next.js App Router project:
- Install Redux Toolkit and React-Redux:
npm install @reduxjs/toolkit react-redux
- Create a Redux slice:
// app/store/counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
const counterSlice = createSlice({
name: "counter",
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
- Set up the Redux store:
// app/store/store.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
- Wrap your application with the Redux Provider:
// app/layout.js
import { Provider } from "react-redux";
import { store } from "./store/store";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<Provider store={store}>{children}</Provider>
</body>
</html>
);
}
- Use Redux state and actions in your components:
// app/page.js
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement } from "./store/counterSlice";
export default function HomePage() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
148 How do you read and set cookies in the App Router? Medium
On the server (server components or route handlers) use cookies() from next/headers to read cookies. To set cookies from a route handler, return a Response with a Set-Cookie header or use a helper library in API routes.
// server component
import { cookies } from "next/headers";
const cookieStore = cookies();
const token = cookieStore.get("token")?.value;
// route handler (set cookie)
export function GET() {
return new Response("ok", {
headers: { "Set-Cookie": "token=abc; HttpOnly; Path=/" },
});
}
149 How can you stream responses from a route handler? Medium
Use the Web Streams API (ReadableStream) in a route handler to stream data progressively to the client. This is useful for large payloads or server-sent updates.
export async function GET() {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("chunk1"));
controller.enqueue(new TextEncoder().encode("chunk2"));
controller.close();
},
});
return new Response(stream, {
headers: { "Content-Type": "text/plain" },
});
}
150 How do you test App Router components and pages? Medium
Use React Testing Library for components and Jest for unit tests. For full page integration you can use next-router-mock or render server components with @testing-library/react plus mocked fetch/next/navigation. For route handler tests, use Supertest or node's fetch mocks.
151 How do you choose between Edge and Node runtimes for route handlers? Medium
Use the Edge runtime for low-latency global responses and where Node APIs are not needed. Choose Node (default) when you require native Node modules, filesystem access, or heavy CPU tasks. You can set export const runtime = 'edge' or leave it for Node.
All 151 questions loaded
Frequently Asked Questions About Next.js Interviews
What do hiring managers evaluate in Next.js technical rounds?
Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.
What are the best interview tips for practicing Next.js questions?
Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.