1. How would you design a scalable Next.js app?

Definition

A scalable Next.js app is designed to handle increasing traffic, data, and complexity without performance degradation.

Architecture Approach

1. Layered Architecture

  • UI Layer (Components)
  • Data Layer (Fetching logic)
  • API Layer (Route handlers / backend)

2. Use App Router

  • Enables server components, streaming, layouts

3. Rendering Strategy

  • SSG → static content
  • ISR → semi-dynamic
  • SSR → real-time

4. CDN + Caching

  • Cache static pages
  • Use edge network

5. Microservices Integration

  • Separate backend services
  • Use APIs

Key Insight

Scalability = proper rendering strategy + caching + modular design


2. How to structure large-scale projects?

Recommended Structure

app/
├── (auth)/
├── (dashboard)/
├── api/
components/
lib/
services/
hooks/
styles/
utils/

Folder Responsibilities

  • app/ → routes
  • components/ → reusable UI
  • services/ → API logic
  • lib/ → utilities/config
  • hooks/ → custom hooks

Best Practices

  • Feature-based structure
  • Avoid deeply nested folders
  • Keep components small

Interview Insight

Structure should scale with team size and features.


3. How to implement modular architecture?

Definition

Modular architecture divides the app into independent, reusable modules.

Approach

1. Feature-Based Modules

features/
├── auth/
├── dashboard/
├── products/

2. Each Module Contains

  • UI components
  • API logic
  • State management

3. Loose Coupling

  • Modules should not depend heavily on each other

Benefits

  • Easy maintenance
  • Reusability
  • Faster development

4. Explain server-first architecture

Definition

Server-first architecture means most of the logic runs on the server by default, not the client.

In Next.js

  • App Router uses Server Components by default

Key Principles

  • Fetch data on server
  • Send minimal JS to client
  • Move logic closer to data

Benefits

  • Better performance
  • Improved security
  • Smaller bundle size

Interview Insight

This is a major shift from traditional client-heavy React apps.


5. How does React Server Components work?

Definition

Server Components render on the server and send HTML (not JS) to the client.

Flow

  1. Server renders component
  2. Fetches data directly
  3. Sends serialized result
  4. Client hydrates only interactive parts

Key Features

  • No client JS overhead
  • Direct database access
  • Better performance

Limitation

  • Cannot use hooks like useState

6. How does streaming improve performance?

Definition

Streaming sends UI in chunks instead of waiting for full page render.

Flow

  1. Render starts
  2. Send partial HTML
  3. Stream remaining content

Example

  • Header loads instantly
  • Data section loads later

Benefits

  • Faster Time-to-First-Byte
  • Better perceived performance

Interview Insight

Important for large, data-heavy pages.


7. How does Suspense work in Next.js?

Definition

Suspense allows components to wait for async data while showing fallback UI.

Example

<Suspense fallback={<p>Loading...</p>}>
<Component />
</Suspense>

How It Works

  • Component suspends until data is ready
  • Fallback UI is shown
  • Content replaces fallback when ready

Integration

  • Works with streaming
  • Used in Server Components

8. How to balance stale vs fresh data?

Problem

  • Fresh data → slower
  • Cached data → may be outdated

Solutions

1. ISR

  • Revalidate after interval

2. Cache-Control

  • Control caching headers

3. SWR Pattern

  • Stale-while-revalidate

Strategy

  • Static data → SSG
  • Semi-dynamic → ISR
  • Real-time → SSR

Interview Insight

This is a trade-off decision problem.


9. How does cache revalidation work?

Definition

Cache revalidation updates cached data after a defined interval or trigger.

Types

1. Time-Based

revalidate: 10

2. On-Demand Revalidation

res.revalidate('/page')

Flow

  1. Cached page served
  2. After interval → new request triggers update
  3. New version replaces old

Benefit

Keeps data fresh without full rebuild.


10. How to fetch authenticated data?

Approaches

1. Server-Side Fetching

const cookies = headers().get('cookie')
  • Use cookies or headers
  • Secure and hidden from client

2. Client-Side Fetching

fetch('/api/data', {
headers: { Authorization: 'Bearer token' }
})

3. Middleware Protection

  • Validate user before request

Best Practice

  • Prefer server-side fetching for sensitive data

Interview Insight

Authentication + data fetching should be secure and efficient.

11. When to use edge runtime?

Definition

Edge runtime allows your code to run closer to the user (CDN edge locations) instead of a centralized server.

When to Use

1. Low Latency Requirements

  • Authentication checks
  • Geo-based personalization

2. Lightweight Logic

  • Middleware
  • Header manipulation

3. Global Applications

  • Content served worldwide

Example

export const runtime = 'edge'

Limitations

  • No full Node.js APIs
  • Limited libraries

Interview Insight

Use edge runtime for fast, lightweight operations, not heavy processing.


13. How to optimize a large-scale Next.js app?

Key Strategies

1. Use Server Components

  • Reduce client bundle size

2. Code Splitting

  • Load only required modules

3. Optimize Images & Fonts

  • Use built-in optimizations

4. Caching Strategy

  • SSG + ISR + CDN

5. Database Optimization

  • Efficient queries
  • Use indexing

6. Monitoring

  • Use logging and analytics

Key Insight

Optimization is a combination of frontend + backend + infrastructure.


14. How to handle heavy traffic?

Strategies

1. CDN Caching

  • Serve static content globally

2. ISR

  • Avoid rebuilding entire app

3. Load Balancing

  • Distribute requests

4. Serverless Scaling

  • Auto-scale functions

5. Rate Limiting

  • Prevent abuse

Interview Insight

Focus on horizontal scaling + caching.


15. How to reduce TTFB (Time To First Byte)?

Techniques

1. Use CDN

  • Serve content from edge

2. Prefer SSG/ISR

  • Avoid runtime rendering

3. Optimize Server Logic

  • Reduce computation time

4. Database Optimization

  • Faster queries

5. Edge Runtime

  • Run logic closer to user

Key Insight

TTFB depends heavily on server response time and location.


16. How to optimize API performance?

Techniques

1. Caching

  • Cache responses

2. Database Optimization

  • Indexing
  • Query optimization

3. Pagination

  • Avoid large payloads

4. Compression

  • Reduce response size

5. Parallel Requests

  • Fetch data concurrently

Example

const [a, b] = await Promise.all([fetchA(), fetchB()])

Interview Insight

API performance is critical for overall app performance.


17. What are parallel routes?

Definition

Parallel routes allow rendering multiple independent UI sections simultaneously.

Example Structure

app/
├── @analytics/
├── @dashboard/
└── layout.js

How It Works

  • Multiple routes rendered in parallel
  • Each slot is independent

Use Cases

  • Dashboard panels
  • Multi-section pages

Benefit

Improves performance and flexibility.


18. What are intercepting routes?

Definition

Intercepting routes allow you to load a route inside another UI context without full navigation.

Example Use Case

  • Open a modal over a page
  • Show details without leaving current screen

Concept

  • Intercepts navigation
  • Keeps existing layout

Interview Insight

Useful for modals and overlays.


19. What are route groups?

Definition

Route groups allow organizing routes without affecting the URL structure.

Syntax

app/
├── (auth)/
├── (dashboard)/

Key Feature

  • Folder name not included in URL

Use Cases

  • Group related routes
  • Separate layouts

Benefit

Improves project organization.


20. How to design nested routing?

Definition

Nested routing allows building hierarchical UI with shared layouts.

Example

app/
├── dashboard/
├── layout.js
├── page.js
└── settings/
└── page.js

How It Works

  • Parent layout wraps child routes
  • Shared UI persists

Benefits

  • Reusable layouts
  • Better UX
  • Cleaner structure

Best Practices

  • Keep layouts reusable
  • Avoid deep nesting

21. What are server actions?

Definition

Server Actions are functions that run directly on the server and can be invoked from client or server components without creating separate API endpoints.

Key Idea

They eliminate the need for /api routes for many use cases.

Example

'use server'

export async function createUser(data) {
// runs on server
}

How They Work

  • Defined in server files
  • Invoked via forms or functions
  • Executed securely on server

Use Cases

  • Form submissions
  • Database mutations
  • Auth operations

22. Benefits of server actions?

Advantages

1. No API Boilerplate

  • No need to create separate endpoints

2. Better Security

  • Runs only on server
  • No exposure to client

3. Simplified Architecture

  • Direct data mutation

4. Performance

  • Reduced network overhead

Interview Insight

Server Actions simplify full-stack development in Next.js.


23. Limitations of server actions?

Constraints

1. Limited Ecosystem

  • Still evolving

2. Debugging Complexity

  • Harder than traditional APIs

3. Not Suitable for Public APIs

  • Cannot expose externally

4. Framework Dependency

  • Tightly coupled with Next.js

Key Insight

Best for internal operations, not external integrations.


24. Alternatives to server actions?

Options

1. API Routes

  • Traditional backend endpoints

2. Route Handlers

  • Modern API approach in App Router

3. External Backend

  • Express, NestJS, etc.

4. GraphQL

  • Flexible querying

Interview Insight

Choose based on complexity and scalability needs.


25. How to implement RBAC (Role-Based Access Control)?

Definition

RBAC restricts access based on user roles (admin, user, etc.).

Steps

1. Define Roles

role: 'admin'

2. Store Role

  • In DB or token

3. Validate Role

if (user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' })
}

4. Protect Routes

  • Middleware or server checks

Best Practice

  • Always validate on server

26. JWT vs NextAuth vs Firebase?

Comparison

FeatureJWTNextAuthFirebase
TypeToken-basedAuth libraryBackend service
ControlFull controlMediumLow
SetupManualEasyEasy
ScalabilityHighHighHigh

JWT

  • Stateless
  • Custom implementation

NextAuth.js

  • Ready-to-use
  • OAuth support

Firebase

  • Full backend solution
  • Auth + DB + hosting

Interview Insight

  • JWT → custom systems
  • NextAuth → Next.js apps
  • Firebase → rapid development

27. How to secure routes?

Techniques

1. Authentication Check

  • Verify user identity

2. Authorization

  • Check roles/permissions

3. Middleware Protection

  • Block unauthorized access

4. Secure Headers

  • Use HTTPS
  • CSP headers

5. Server Validation

  • Never trust client

Example

if (!user) return redirect('/login')

28. How to handle auth in middleware?

Definition

Middleware can enforce authentication before request reaches route.

Example

import { NextResponse } from 'next/server'

export function middleware(req) {
const token = req.cookies.get('token')

if (!token) {
return NextResponse.redirect(new URL('/login', req.url))
}

return NextResponse.next()
}

Use Cases

  • Protect routes
  • Redirect unauthenticated users

Key Insight

Runs early → improves security and performance.


29. Best practices for API routes?

Guidelines

1. Keep Handlers Small

  • Single responsibility

2. Validate Input

  • Prevent invalid data

3. Handle Errors Properly

try {} catch (err) {}

4. Use Proper Status Codes

  • 200, 400, 401, 500

5. Secure Endpoints

  • Auth + rate limiting

6. Optimize Performance

  • Cache responses

Interview Insight

API routes should be secure, scalable, and maintainable.


30. How to validate input?

Methods

1. Manual Validation

if (!email) throw new Error('Invalid')

2. Schema Validation

  • Use libraries like Zod, Joi
import { z } from 'zod'

const schema = z.object({
email: z.string().email()
})

3. Server-Side Validation

  • Always validate on server

Best Practices

  • Validate early
  • Sanitize inputs
  • Prevent injection attacks

Interview Insight

Input validation is critical for security and data integrity.


41. How to generate sitemap?

Definition

A sitemap is an XML file that lists all pages of a website to help search engines crawl efficiently.

Methods

1. Static Sitemap

  • Generate at build time
// app/sitemap.js
export default function sitemap() {
return [
{ url: 'https://example.com', lastModified: new Date() }
]
}

2. Dynamic Sitemap

  • Fetch routes from database

Best Practices

  • Include all important pages
  • Update regularly
  • Add to robots.txt

Interview Insight

Important for SEO and indexing large apps.


42. How to optimize Core Web Vitals?

Key Metrics

  • LCP (Largest Contentful Paint)
  • FID (First Input Delay)
  • CLS (Cumulative Layout Shift)

Optimization Techniques

1. Use next/image

  • Optimized images

2. Reduce JS Bundle

  • Code splitting

3. Use SSG/ISR

  • Faster load

4. Optimize Fonts

  • Use next/font

5. Avoid Layout Shift

  • Set image dimensions

Interview Insight

Core Web Vitals directly impact SEO rankings.


43. Edge functions vs serverless?

Comparison

FeatureEdge FunctionsServerless
LocationCDN edgeCentral server
LatencyVery lowModerate
RuntimeLimitedFull Node.js
Use CaseLightweight logicHeavy processing

Explanation

  • Edge → fast, global
  • Serverless → powerful, flexible

Interview Insight

Choose based on latency vs capability.


44. How to implement geo-based routing?

Definition

Serve content based on user location.

Approach

1. Middleware

export function middleware(req) {
const country = req.geo?.country

if (country === 'IN') {
return Response.redirect('/in')
}
}

2. Headers

  • Use location headers from CDN

Use Cases

  • Localization
  • Region-specific content

45. How to use middleware for auth?

Flow

  1. Request comes in
  2. Middleware checks auth token
  3. Redirect or allow

Example

import { NextResponse } from 'next/server'

export function middleware(req) {
const token = req.cookies.get('token')

if (!token) {
return NextResponse.redirect('/login')
}

return NextResponse.next()
}

Benefits

  • Centralized auth logic
  • Improves performance

46. Custom error boundaries?

Definition

Error boundaries catch runtime errors in React components.

Example

'use client'

class ErrorBoundary extends React.Component {
componentDidCatch(error) {
console.error(error)
}

render() {
return this.props.children
}
}

In Next.js

  • Use error.js for route-level boundaries

Use Case

  • Prevent app crash
  • Show fallback UI

47. How to handle global errors?

Methods

1. Global error.js

app/error.js

2. Logging

  • Log errors to monitoring tools

3. Graceful UI

  • Show fallback UI

Best Practice

Never expose sensitive error details to users.


48. How to avoid crashes?

Strategies

1. Error Boundaries

  • Catch UI errors

2. Input Validation

  • Prevent invalid data

3. Try-Catch Blocks

try {} catch (e) {}

4. Defensive Coding

  • Handle null/undefined

5. Monitoring

  • Track runtime errors

Interview Insight

Reliability is as important as performance.


49. Best security practices?

Key Practices

1. Use HTTPS

  • Encrypt data

2. Secure Cookies

  • HttpOnly, Secure

3. Validate Inputs

  • Prevent injection

4. Use CSP Headers

  • Prevent XSS

5. Authentication & Authorization

  • Protect routes

6. Rate Limiting

  • Prevent abuse

Interview Insight

Security must be considered at every layer.


50. How to prevent API abuse?

Techniques

1. Rate Limiting

  • Limit requests per user

2. Authentication

  • Require valid tokens

3. CAPTCHA

  • Prevent bots

4. Throttling

  • Slow down repeated requests

5. Logging & Monitoring

  • Detect unusual activity

Example

if (requests > limit) {
return res.status(429).json({ error: 'Too many requests' })
}

Interview Insight

API abuse prevention is critical for scalability and security.

51. CSRF / XSS protection?

Definitions

  • CSRF (Cross-Site Request Forgery) → tricks a user into making unwanted requests
  • XSS (Cross-Site Scripting) → injects malicious scripts into your app

CSRF Protection

Techniques

  • Use CSRF tokens
  • SameSite cookies (SameSite=Strict)
  • Validate origin headers
res.setHeader('Set-Cookie', 'token=abc; SameSite=Strict')

XSS Protection

Techniques

  • Escape user input
  • Use React (auto-escapes by default)
  • Avoid dangerouslySetInnerHTML
  • Use CSP headers

Interview Insight

Security must be enforced at both frontend and backend layers.


52. Global state strategies?

Options

1. React Context

  • Built-in
  • Good for small apps

2. Redux

  • Centralized state
  • Complex apps

3. Zustand

  • Lightweight state management

4. Server State (Recommended)

  • Fetch on server (RSC)
  • Avoid unnecessary global state

Best Practice

  • Prefer server state first
  • Use global state only when necessary

53. Redux vs Context vs Zustand?

Comparison

FeatureReduxContextZustand
ComplexityHighLowLow
PerformanceGoodCan re-renderOptimized
SetupHeavySimpleSimple
Use CaseLarge appsSmall appsMedium apps

Summary

  • Redux → enterprise-level
  • Context → simple global state
  • Zustand → modern lightweight solution

Interview Insight

Avoid over-engineering state management.


54. How to build a dashboard with auth?

Architecture

1. Authentication

  • Use cookies or tokens

2. Protected Routes

  • Middleware checks auth

3. Layout Structure

app/
├── dashboard/
├── layout.js
├── page.js

4. Data Fetching

  • Server-side for secure data

5. UI Components

  • Charts, tables, widgets

Flow

  1. User logs in
  2. Token stored
  3. Middleware validates
  4. Dashboard loads

55. How to implement pagination/filtering?

Pagination

Example

fetch(`/api/products?page=1&limit=10`)

Types

  • Offset-based
  • Cursor-based (better for large data)

Filtering

fetch(`/api/products?category=tech`)

Best Practices

  • Perform on server
  • Use query params
  • Combine with caching

56. How to handle file uploads?

Methods

1. API Route

export default function handler(req, res) {
// handle file upload
}

2. Use FormData

const formData = new FormData()
formData.append('file', file)

3. Cloud Storage

  • Upload to S3, Cloudinary

Best Practice

  • Do not store files on server
  • Use external storage

57. How to implement GraphQL?

Steps

1. Setup Server

  • Apollo Server

2. Create Schema

type Query {
user: String
}

3. Fetch Data

  • Use Apollo Client
useQuery(GET_USER)

Integration

  • Can run inside API routes or external backend

Interview Insight

GraphQL is useful for flexible data fetching.


58. How to migrate Pages → App Router?

Steps

1. Move pages to /app

  • Replace pages/ with app/

2. Replace Data Fetching

  • getStaticProps → fetch in components

3. Use Layouts

  • Add layout.js

4. Convert Components

  • Use Server/Client components

Challenges

  • Learning curve
  • Refactoring required

59. When to use App Router vs Pages Router?

Comparison

Use CaseApp RouterPages Router
New projectsYesNo
Legacy appsNoYes
Advanced featuresYesLimited

Decision

  • Use App Router for modern apps
  • Use Pages Router for existing systems

60. Limitations of Next.js?

Key Limitations

1. Learning Curve

  • Many concepts (SSR, ISR, RSC)

2. Server Dependency

  • Requires backend understanding

3. Build Time

  • Large apps → slow builds

4. Vendor Lock-in

  • Tight coupling with framework

5. Edge Limitations

  • Limited APIs

Interview Insight

Trade-offs exist between power and complexity.


61. Is Next.js suitable for enterprise apps?

Answer: Yes, with conditions

Why Suitable

1. Performance

  • SSR, SSG, ISR

2. Scalability

  • Serverless + CDN

3. Full-stack capability

  • API routes, middleware

4. Ecosystem

  • Strong community

Considerations

1. Architecture Planning

  • Must design properly

2. Team Expertise

  • Requires experienced developers

3. Monitoring

  • Needs observability tools

Interview Insight

Next.js is widely used in enterprise apps, but success depends on architecture and best practices.