1. What is Next.js?
Next.js is a React-based full-stack framework that enables developers to build production-ready web applications with built-in features like routing, rendering strategies, and performance optimizations.
Key Idea
React handles UI development, while Next.js provides a complete framework including backend capabilities and optimizations.
Core Capabilities
- Hybrid rendering (SSR, SSG, CSR)
- API routes
- File-based routing
- Built-in performance optimizations
Use Cases
- SEO-friendly websites
- E-commerce platforms
- SaaS applications
- Blogs and content-driven apps
2. How is Next.js different from React?
Core Difference
| Feature | React | Next.js |
|---|---|---|
| Type | Library | Framework |
| Routing | Manual setup | Built-in |
| Rendering | Client-side | SSR, SSG, CSR |
| SEO | Limited | Strong |
| Backend | Not included | API routes included |
Explanation
React focuses only on UI, while Next.js provides a complete application architecture including routing, rendering, and backend support.
Analogy
React is like an engine, while Next.js is a complete car.
3. What problems does Next.js solve?
Problems in Traditional React Apps
- Poor SEO due to client-side rendering
- Slow initial page load
- Manual routing setup
- No built-in backend support
- Performance optimization complexity
Solutions Provided by Next.js
| Problem | Solution |
|---|---|
| SEO issues | SSR and SSG |
| Slow loading | Pre-rendering |
| Routing complexity | File-based routing |
| Backend absence | API routes |
| Optimization overhead | Built-in optimizations |
Result
- Improved performance
- Better SEO
- Simplified development
4. What are the key features of Next.js?
Core Features
- File-Based Routing
- Pre-rendering
- Server-Side Rendering (SSR)
- Static Site Generation (SSG)
- API Routes
- Image Optimization
- Code Splitting
- Middleware support
- App Router (modern routing system)
5. What is file-based routing in Next.js?
Definition
A routing system where the folder and file structure automatically defines application routes.
Example
pages/
├── index.js → /
├── about.js → /about
└── blog/
└── post.js → /blog/post
Benefits
- No need for external routing libraries
- Easy to manage
- Convention-based approach
6. What is the purpose of the pages directory?
Definition
The /pages directory is the traditional routing system in Next.js.
Responsibilities
- Defines routes
- Exports React components
- Supports SSR and SSG functions
Special Files
-
pages/index.js→ Home page -
pages/_app.js→ Global app wrapper -
pages/_document.js→ Custom HTML structure -
pages/api/*→ API endpoints
Example
export default function Home() {
return <h1>Hello Next.js</h1>
}
7. What is the app directory in Next.js?
Definition
The /app directory is the modern routing system introduced in Next.js 13 and above.
Key Concepts
- Uses React Server Components
- Supports nested layouts
- Enables streaming and suspense
Structure Example
app/
├── page.js → /
├── layout.js → shared layout
└── blog/
└── page.js → /blog
Advantages
- Better performance
- Cleaner layout handling
- Server-first architecture
8. What is pre-rendering?
Definition
Pre-rendering means generating HTML before it is sent to the browser.
Importance
- Faster loading
- Improved SEO
- Better user experience
Types
- Static Generation (SSG)
- Server-Side Rendering (SSR)
9. What is Server-Side Rendering (SSR)?
Definition
HTML is generated on the server for every request.
Process
- User sends request
- Server fetches data
- Server generates HTML
- Response is sent to browser
Example
export async function getServerSideProps() {
return {
props: { data: "SSR Data" }
}
}
Use Cases
- Dynamic data
- Personalized content
- Real-time applications
Drawbacks
- Higher server load
- Slower compared to static pages
10. What is Static Site Generation (SSG)?
Definition
HTML is generated at build time and served as static files.
Process
- Pages are generated during build
- Stored as static assets
- Delivered instantly via CDN
Example
export async function getStaticProps() {
return {
props: { data: "Static Data" }
}
}
Use Cases
- Blogs
- Documentation
- Marketing pages
Benefits
- Very fast performance
- Reduced server load
- CDN-friendly
Limitations
- Not suitable for frequently changing data
11. How does routing work in Next.js?
Definition
Next.js uses a file-based routing system, where the folder and file structure automatically define application routes.
How It Works
- Each file inside
/pagesor/appbecomes a route - No need for external routing libraries
- Nested folders create nested routes
Example
pages/
├── index.js → /
├── about.js → /about
└── blog/
└── post.js → /blog/post
Key Points
- Automatic route generation
- Supports dynamic and nested routes
- Works differently in:
-
/pages(traditional router) -
/app(App Router with layouts and server components)
-
12. What is dynamic routing?
Definition
Dynamic routing allows you to create routes with dynamic parameters.
Syntax
Use square brackets [param] in file names.
Example
pages/blog/[id].js
Route:
/blog/1
/blog/abc
Accessing Params
import { useRouter } from 'next/router'
const router = useRouter()
const { id } = router.query
Use Cases
- Blog posts
- Product pages
- User profiles
13. What is a catch-all route?
Definition
A catch-all route captures multiple dynamic segments.
Syntax
pages/docs/[...slug].js
Example URLs
/docs/a
/docs/a/b
/docs/a/b/c
Output
slug = ['a', 'b', 'c']
Optional Catch-All
pages/docs/[[...slug]].js
Difference
-
[...slug]→ requires at least one segment -
[[...slug]]→ optional (can match/docsas well)
14. What is the Link component?
Definition
The Link component is used for client-side navigation between pages in Next.js.
Example
import Link from 'next/link'
<Link href="/about">Go to About</Link>
Key Features
- Prevents full page reload
- Enables faster navigation
- Prefetches pages in background
Why It Matters
Improves performance and user experience compared to traditional <a> tags.
15. What is useRouter?
Definition
useRouter is a hook that provides access to the router object in Next.js.
Example
import { useRouter } from 'next/router'
const router = useRouter()
console.log(router.pathname)
console.log(router.query)
Capabilities
- Access route parameters
- Navigate programmatically
- Get current route info
Common Properties
-
pathname -
query -
asPath
16. Difference between push and replace?
Definition
| Method | Behavior |
|---|---|
| push | Adds new entry to browser history |
| replace | Replaces current history entry |
Example
router.push('/home')
router.replace('/login')
Key Difference
-
pushallows user to go back -
replaceprevents going back
Use Cases
- push → normal navigation
- replace → redirects (e.g., after login)
17. How do you navigate programmatically?
Definition
Programmatic navigation is done using the router API.
Example
import { useRouter } from 'next/router'
const router = useRouter()
const handleClick = () => {
router.push('/dashboard')
}
Other Methods
-
router.replace() -
router.back()
Use Cases
- After form submission
- Authentication redirects
- Conditional navigation
18. Difference between SSR and CSR?
Comparison
| Feature | SSR | CSR |
|---|---|---|
| Rendering | Server | Browser |
| Initial Load | Faster content | Slower |
| SEO | Good | Poor |
| Interactivity | After hydration | Immediate after JS loads |
Explanation
- SSR sends ready HTML
- CSR renders UI in browser using JavaScript
Summary
SSR improves SEO and performance, while CSR is better for highly interactive apps.
19. What is Client-Side Rendering (CSR)?
Definition
Client-Side Rendering means rendering happens in the browser using JavaScript.
How It Works
- Browser loads minimal HTML
- JavaScript loads
- React renders UI
Example
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(data => setData(data))
}, [])
Advantages
- Rich interactivity
- Smooth user experience after load
Disadvantages
- Poor SEO
- Slower initial load
20. What is Incremental Static Regeneration (ISR)?
Definition
ISR allows static pages to be updated after deployment without rebuilding the entire site.
How It Works
- Page is generated at build time
- After a specified time, it is regenerated in the background
Example
export async function getStaticProps() {
return {
props: { data: "ISR Data" },
revalidate: 10
}
}
Explanation
-
revalidate: 10→ page updates every 10 seconds
Benefits
- Combines SSG performance with dynamic updates
- Reduces build time
- Keeps content fresh
Use Cases
- News websites
- E-commerce product pages
- Frequently updated content
Final Summary (Interview Tip)
- Routing in Next.js is file-based and supports dynamic patterns
- Navigation can be done via
Linkor programmatically usinguseRouter - Rendering strategies include SSR, CSR, and ISR
- ISR is a hybrid approach combining static performance with dynamic updates
If you want, I can continue with advanced topics like middleware, caching strategies, server components, and edge functions in the same structured format.
21. What is static optimization?
Definition
Static Optimization is a feature in Next.js where pages are automatically pre-rendered as static HTML at build time if they do not require dynamic data.
How It Works
- If a page does NOT use:
-
getServerSideProps -
getInitialProps
-
- Then Next.js automatically converts it into a static page
Example
export default function Home() {
return <h1>Static Page</h1>
}
Key Benefits
- Faster load time
- Better performance
- CDN caching support
Important Insight
No configuration is needed. Next.js decides automatically.
22. How do you create a Next.js app?
Method 1: Using CLI (Recommended)
npx create-next-app@latest my-app
cd my-app
npm run dev
Method 2: Using Yarn
yarn create next-app my-app
Steps Explained
- Create project using CLI
- Navigate into project folder
- Start development server
Result
App runs locally in development mode.
23. What is Create Next App?
Definition
Create Next App is an official tool that helps you quickly bootstrap a Next.js application with pre-configured settings.
Features
- Pre-configured project structure
- Built-in tooling (Webpack / Turbopack)
- TypeScript support (optional)
- ESLint setup
Benefits
- Saves setup time
- Reduces configuration complexity
- Ensures best practices
24. What is the default port?
Answer
The default development server runs on:
http://localhost:3000
Explanation
When you run:
npm run dev
Next.js starts the server on port 3000 by default.
25. How to change the default port?
Method 1: Command Line
npm run dev -- -p 4000
Method 2: Direct Command
next dev -p 4000
Method 3: Environment Variable
PORT=4000 npm run dev
Use Case
Useful when port 3000 is already in use or for custom environments.
26. How do you add CSS in Next.js?
Methods
1. Global CSS
Import in _app.js:
import '../styles/globals.css'
2. CSS Modules
Scoped CSS per component.
3. Inline CSS
Using style prop.
<div style={{ color: 'red' }}>Text</div>
4. Styled JSX
Built-in scoped CSS solution.
5. External Libraries
- Tailwind CSS
- Sass
Key Insight
Next.js supports multiple styling approaches out of the box.
27. What is CSS Modules?
Definition
CSS Modules allow you to write scoped CSS, meaning styles apply only to a specific component.
File Naming
Component.module.css
Example
/* styles.module.css */
.title {
color: blue;
}
import styles from './styles.module.css'
<h1 className={styles.title}>Hello</h1>
Benefits
- Avoids global CSS conflicts
- Improves maintainability
- Component-level styling
28. What is Styled JSX?
Definition
Styled JSX is a built-in CSS-in-JS solution in Next.js that allows scoped styling within components.
Example
export default function Home() {
return (
<>
<h1>Hello</h1>
<style jsx>{`
h1 {
color: red;
}
`}</style>
</>
)
}
Features
- Scoped styles by default
- No external library needed
- Supports dynamic styling
Use Case
Useful for component-level styling without separate CSS files.
29. How to use Tailwind CSS?
Step-by-Step Setup
1. Install dependencies
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
2. Configure Tailwind
// tailwind.config.js
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./app/**/*.{js,ts,jsx,tsx}"
]
3. Add Tailwind to CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
4. Use in components
<h1 className="text-blue-500">Hello</h1>
Benefits
- Utility-first styling
- Faster UI development
- Highly customizable
30. What is the public folder?
Definition
The public folder is used to store static assets that can be accessed directly.
Examples of Files
- Images
- Fonts
- Icons
- Static files
Usage
<img src="/logo.png" />
Explanation
- Files inside
publicare served at the root (/) - No need for import statements
Key Points
- Used for static resources
- Not processed by Webpack
- Accessible directly via URL
31. How do you serve static files?
Definition
Static files in Next.js are served from the public directory and are accessible directly via URL.
How It Works
- Any file placed inside
/publicis served at the root path/ - No import or bundling required
Example
Folder:
public/logo.png
Usage:
<img src="/logo.png" />
Key Points
- Files are not processed by Webpack
- Best for images, fonts, and static assets
- Efficient and CDN-friendly
32. What is the Head component?
Definition
The Head component is used to modify the <head> section of a page.
Example
import Head from 'next/head'
export default function Page() {
return (
<>
<Head>
<title>My Page</title>
<meta name="description" content="My page description" />
</Head>
<h1>Hello</h1>
</>
)
}
Use Cases
- Setting page title
- Adding meta tags
- Linking stylesheets or scripts
Key Insight
Each page can have its own <head> configuration.
33. Why is SEO important in Next.js?
Definition
SEO (Search Engine Optimization) improves a website’s visibility in search engines.
Why Next.js Helps
- Supports SSR and SSG
- Pre-rendered HTML is crawlable
- Faster load times improve rankings
Benefits
- Higher search ranking
- Better user reach
- Improved performance metrics
Interview Insight
CSR-only apps struggle with SEO, while Next.js solves this with pre-rendering.
34. How do you add meta tags?
Method
Use the Head component.
Example
import Head from 'next/head'
<Head>
<meta name="keywords" content="Next.js, React" />
<meta name="author" content="Developer" />
</Head>
Common Meta Tags
- description
- keywords
- viewport
- Open Graph (for social sharing)
Importance
Meta tags help search engines understand page content.
35. What is the Image component?
Definition
The Image component is a built-in Next.js component for optimized image rendering.
Example
import Image from 'next/image'
<Image
src="/logo.png"
width={200}
height={100}
alt="Logo"
/>
Features
- Automatic resizing
- Lazy loading
- Responsive images
Advantage
Improves performance compared to standard <img>.
36. What is image optimization?
Definition
Image optimization is the process of delivering images in the most efficient format and size.
How Next.js Handles It
- Automatic resizing
- WebP/modern formats
- Lazy loading
- CDN delivery
Benefits
- Faster page load
- Reduced bandwidth usage
- Better Core Web Vitals
37. What is Fast Refresh?
Definition
Fast Refresh is a feature that provides instant feedback during development.
How It Works
- Updates only changed modules
- Preserves component state
- Refreshes UI instantly
Example Scenario
Change a component → UI updates immediately without full reload.
Benefit
Improves developer productivity.
38. What is HMR (Hot Module Replacement)?
Definition
HMR is a technique that allows updating modules in the browser without reloading the entire page.
How It Works
- Replaces only modified code
- Keeps app running
- Avoids full refresh
Difference from Fast Refresh
| Feature | HMR | Fast Refresh |
|---|---|---|
| Scope | General | React-specific |
| State Preservation | Not always | Yes |
| Usage | Webpack feature | Next.js optimized |
39. What are API routes?
Definition
API routes allow you to create backend endpoints inside a Next.js app.
Location
pages/api/*
Example
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello API' })
}
Access
/api/hello
Use Cases
- Form handling
- Authentication
- Database operations
40. How do you create an API route?
Steps
1. Create file
pages/api/user.js
2. Export handler function
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ name: 'John' })
}
}
Request Object (req)
- method
- query
- body
Response Object (res)
- status()
- json()
- send()
Key Points
- Runs on server side
- No client bundle impact
- Can connect to databases
41. What is client-side data fetching?
Definition
Client-side data fetching means fetching data in the browser after the page has loaded, instead of pre-rendering it on the server.
How It Works
- Page loads first
- JavaScript runs in the browser
- Data is fetched using APIs
Example
import { useEffect, useState } from 'react'
export default function Page() {
const [data, setData] = useState(null)
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData)
}, [])
return <div>{data ? data.message : 'Loading...'}</div>
}
Use Cases
- User dashboards
- Real-time updates
- Non-SEO critical data
Pros
- Dynamic updates
- Reduced server load
Cons
- Slower initial data display
- Not ideal for SEO
42. What is next.config.js?
Definition
next.config.js is the configuration file for customizing Next.js behavior.
Example
module.exports = {
reactStrictMode: true,
images: {
domains: ['example.com']
}
}
What You Can Configure
- Environment variables
- Image domains
- Redirects and rewrites
- Webpack customization
Importance
Central place to control application-level settings.
43. What are environment variables?
Definition
Environment variables are external configuration values used to store sensitive or environment-specific data.
Example
NEXT_PUBLIC_API_URL=https://api.example.com
Usage
process.env.NEXT_PUBLIC_API_URL
Types
- Server-only variables
- Public variables (prefixed with
NEXT_PUBLIC_)
Benefits
- Secure handling of secrets
- Easy environment switching (dev, staging, prod)
44. How do you deploy a Next.js app?
Common Methods
1. Using Vercel (Recommended)
- Push code to GitHub
- Connect repo to Vercel
- Automatic deployment
2. Manual Deployment
npm run build
npm start
3. Docker / Cloud Platforms
- AWS
- Azure
- Google Cloud
Key Steps
- Build application
- Optimize assets
- Deploy to hosting platform
45. What is Vercel?
Definition
Vercel is a cloud platform designed for deploying and hosting Next.js applications.
Key Features
- Zero-config deployment
- Automatic scaling
- Edge network (CDN)
- Built-in CI/CD
Why It Matters
- Created by the makers of Next.js
- Optimized for performance and ease of use
46. What is middleware?
Definition
Middleware is code that runs before a request is completed, allowing you to modify the request or response.
Location
middleware.js
Example
import { NextResponse } from 'next/server'
export function middleware(request) {
return NextResponse.redirect(new URL('/login', request.url))
}
Use Cases
- Authentication
- Logging
- Redirects
- Localization
Key Insight
Runs at the edge before reaching the actual route.
47. What is next/script?
Definition
next/script is used to optimize loading of third-party scripts.
Example
import Script from 'next/script'
<Script
src="https://example.com/script.js"
strategy="lazyOnload"
/>
Loading Strategies
-
beforeInteractive -
afterInteractive -
lazyOnload
Benefits
- Improves performance
- Controls script execution timing
48. What is AMP in Next.js?
Definition
AMP (Accelerated Mobile Pages) is a framework for building fast-loading mobile web pages.
Usage
export const config = { amp: true }
Benefits
- Faster mobile performance
- Improved SEO ranking
Limitation
- Restricted JavaScript usage
- Less flexibility
Interview Insight
AMP is less commonly used today due to modern performance optimizations.
49. What is TypeScript support?
Definition
Next.js provides built-in support for TypeScript, enabling type-safe development.
Setup
touch tsconfig.json
Next.js automatically configures TypeScript.
Example
type Props = {
name: string
}
export default function Page({ name }: Props) {
return <h1>{name}</h1>
}
Benefits
- Type safety
- Better developer experience
- Fewer runtime errors
50. What is next/image?
Definition
next/image is a Next.js component used for automatic image optimization.
Example
import Image from 'next/image'
<Image
src="/photo.jpg"
width={300}
height={200}
alt="Photo"
/>
Features
- Lazy loading
- Responsive sizing
- Automatic format optimization
Difference from <img>
| Feature | <img> | next/image |
|---|---|---|
| Optimization | Manual | Automatic |
| Lazy Loading | Optional | Built-in |
| Performance | Basic | Optimized |
Key Insight
It significantly improves performance and Core Web Vitals.
51. What is next/link?
Definition
next/link is a built-in component used for client-side navigation between pages in Next.js.
Example
import Link from 'next/link'
<Link href="/about">Go to About</Link>
How It Works
- Wraps anchor-like navigation
- Prevents full page reload
- Uses client-side routing
Features
- Prefetches pages in the background
- Improves navigation speed
- Preserves application state
Interview Insight
Always prefer next/link over <a> for internal navigation.
52. What is global CSS?
Definition
Global CSS is styling that applies across the entire application.
Where to Define
In /styles/globals.css, imported in _app.js.
Example
import '../styles/globals.css'
Use Cases
- Reset styles
- Typography
- Common layout styles
Key Rule
Global CSS can only be imported in _app.js (in the pages router).
53. What is component-level CSS?
Definition
Component-level CSS refers to styles that are scoped to a specific component.
Methods
- CSS Modules
- Styled JSX
Example (CSS Module)
.button {
background: blue;
}
import styles from './Button.module.css'
<button className={styles.button}>Click</button>
Benefits
- Avoids style conflicts
- Improves maintainability
- Encapsulation of styles
54. What is static export?
Definition
Static export means generating a fully static version of your Next.js app that can be hosted without a Node.js server.
Command
next build
next export
Output
- Generates static HTML, CSS, JS files
- Stored in
out/directory
Use Cases
- Static hosting (Netlify, GitHub Pages)
- Simple websites
Limitation
- No SSR or API routes
55. What is SEO optimization?
Definition
SEO optimization is the process of improving a website’s visibility and ranking in search engines.
How Next.js Helps
- Pre-rendering (SSR, SSG)
- Fast loading pages
- Easy meta tag management
Key Techniques
- Proper meta tags
- Semantic HTML
- Image optimization
- Performance tuning
Interview Insight
Next.js is preferred for SEO-heavy applications due to pre-rendering.
56. What is a custom 404 page?
Definition
A custom 404 page is shown when a user navigates to a non-existent route.
How to Create
pages/404.js
Example
export default function Custom404() {
return <h1>Page Not Found</h1>
}
Benefits
- Better user experience
- Branding consistency
- Helpful navigation options
57. What is _error.js?
Definition
_error.js is used to handle runtime errors in Next.js applications.
Location
pages/_error.js
Example
function Error({ statusCode }) {
return <p>Error: {statusCode}</p>
}
export default Error
Use Case
- Display custom error UI
- Handle server/client errors
Note
More commonly used in older Next.js setups; App Router uses different patterns.
58. What is _app.js?
Definition
_app.js is the top-level component that wraps all pages.
Purpose
- Initialize pages
- Maintain layout
- Inject global styles
Example
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Use Cases
- Global CSS import
- Layout wrappers
- State providers (Redux, Context)
59. What is _document.js?
Definition
_document.js is used to customize the HTML document structure.
Scope
- Runs only on server
- Controls
<html>,<body>, etc.
Example
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
Use Cases
- Adding fonts
- Setting language attributes
- Customizing HTML structure
60. Difference between _app.js and _document.js?
Comparison
| Feature | _app.js | _document.js |
|---|---|---|
| Purpose | Page wrapper | HTML structure |
| Runs On | Client + Server | Server only |
| Use Case | Layout, state | HTML customization |
| Access to DOM | Yes | No |
Explanation
-
_app.jscontrols how pages behave -
_document.jscontrols how the document is structured
Key Insight
Use _app.js for application logic and _document.js for low-level HTML customization.