Next.js Interview Questions (3 Years Experience)

 

Next.js Interview Questions (3 Years Experience)


1. What are the main differences between Next.js and React.js?

React.js is a JavaScript library focused on building user interfaces, especially for single-page applications.

Next.js is a framework built on top of React that provides features like server-side rendering, static site generation, file-based routing, and full-stack capabilities.

Key Differences:

Feature React.js Next.js
Type Library Framework
Routing Requires external libraries like react-router Built-in file-based routing
Rendering Client-side rendering only SSR, SSG, ISR, CSR
API Support No backend support Has built-in API routes
SEO Less SEO-friendly SEO-friendly with SSR/SSG
Code Splitting Manual setup Automatic
Image Optimization Manual setup Built-in next/image
Deployment Requires custom setup Optimized for Vercel

2. What are the main differences between getStaticProps, getServerSideProps, and getInitialProps?

  • getStaticProps: Fetches data at build time. Used for static generation.
  • getServerSideProps: Fetches data on every request. Used for server-side rendering.
  • getInitialProps: Legacy method. Runs on both server and client. Not recommended for new apps.

3. How does file-based routing work in Next.js?

Each file in the pages/ directory corresponds to a route. For example:

  • pages/index.js/
  • pages/about.js/about
  • pages/blog/[slug].js → dynamic route /blog/:slug

4. What is Incremental Static Regeneration (ISR) in Next.js?

ISR allows you to update static pages after deployment without rebuilding the whole site. You set a revalidate time in getStaticProps:

export async function getStaticProps() {
  return {
    props: { ... },
    revalidate: 10 // seconds
  }
}

5. What are API routes in Next.js?

API routes are backend functions you can define inside pages/api/. Each file becomes an API endpoint. Example:

pages/api/hello.js

export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from API!' });
}


6. How does Next.js handle image optimization?

Using the next/image component, which provides automatic:

  • Lazy loading
  • Resizing
  • WebP conversion
  • Responsive loading

Example:

jsx
CopyEdit
import Image from 'next/image'

<Image src="/profile.jpg" width={300} height={300} alt="Profile" />


7. How do you implement SEO in Next.js?

  • Use <Head> from next/head to set meta tags.
  • Use SSR or SSG for better SEO.
  • Add Open Graph and Twitter meta tags for social sharing.

8. How do you deploy a Next.js app?

Common platforms:

  • Vercel (official and best-supported)
  • Netlify
  • AWS / DigitalOcean / Custom Node server

For Vercel:

  • Push code to GitHub
  • Connect repo on Vercel
  • Automatic builds and deployment

9. How do you protect routes in Next.js?

Options:

  • Use a wrapper component with authentication logic
  • Use middleware (middleware.ts) to check auth tokens
  • Use SSR with session validation in getServerSideProps

10. How do environment variables work in Next.js?

  • .env.local, .env.production, etc.
  • Prefix variables with NEXT_PUBLIC_ to expose them to the client:
env
CopyEdit
NEXT_PUBLIC_API_URL=https://api.example.com

In code:

const apiUrl = process.env.NEXT_PUBLIC_API_URL;


11. How do you optimize performance in Next.js?

  • Enable Image component
  • Use next/script for third-party scripts
  • Lazy load components
  • Reduce bundle size with dynamic imports
  • Use React.memo or useMemo

12. How does code splitting work in Next.js?

Next.js automatically splits code by route. Only the necessary JavaScript is loaded per page. You can further optimize with:

import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('../components/HeavyComponent'))


13. What is the App Router vs Pages Router in Next.js?

  • Pages Router (Classic): Based on pages/, uses getStaticProps, getServerSideProps, etc.
  • App Router (New): Based on app/, uses Server Components, layout.js, loading.js, error.js, and React 18 features.

14. How do you handle API integration in Next.js?

  • Use built-in API routes for backend logic.
  • Use fetch, axios, or SWR/React Query for client-side fetching.
  • Use getServerSideProps for SSR API calls.

15. What is Middleware in Next.js?

Middleware runs before a request is completed, allowing redirection, authentication, etc.

Example:

// middleware.ts
import { NextResponse } from 'next/server'

export function middleware(request) {
  const token = request.cookies.get('token')
  if (!token) return NextResponse.redirect('/login')
}


16. What are Layouts in Next.js and how are they implemented?

In the Pages Router (traditional pages/ folder):

You can implement layouts by creating a wrapper component around your pages.

Example:

// components/Layout.js
export default function Layout({ children }) {
  return (
    <div>
      <header>My Header</header>
      <main>{children}</main>
      <footer>My Footer</footer>
    </div>
  );
}

Use it in your _app.js:

// pages/_app.js
import Layout from '../components/Layout';

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}


In the App Router (app/ folder introduced in Next.js 13+):

Layouts are first-class citizens.

Structure:

markdown
CopyEdit
app/
  layout.js       ← Global layout
  page.js         ← Route component
  about/
    layout.js     ← Nested layout
    page.js       ← About page

app/layout.js:

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <header>Global Header</header>
        {children}
        <footer>Footer</footer>
      </body>
    </html>
  );
}


17. What is Dynamic Import in Next.js and when should you use it?

Dynamic import allows you to load a component only when it’s needed — a form of code-splitting to improve performance.

Use Case:

  • Heavy components (e.g., charts, modals)
  • Components only used on the client side

Example:

import dynamic from 'next/dynamic';

// Load Chart component only on client side
const Chart = dynamic(() => import('../components/Chart'), {
  ssr: false,
  loading: () => <p>Loading...</p>,
});

Benefits:

  • Reduces initial bundle size
  • Improves page load time

18. What are Server Components in Next.js?

Server Components (introduced in Next.js 13 with the App Router) allow components to be rendered on the server by default, without sending JavaScript to the client.

Key Points:

  • Write async components (e.g., async function Page()).
  • Use database queries directly inside components.
  • No client-side JavaScript overhead.
  • Fully compatible with streaming and Suspense.

Example:


// app/page.js (Server Component)
export default async function Page() {
  const data = await fetchData();
  return <div>{data.name}</div>;
}

If you need a Client Component:

'use client';

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}


19. How does Static Site Generation (SSG) work in Next.js?

Static Site Generation (SSG) is a rendering method where HTML is pre-rendered at build time and served as static files.

Used via getStaticProps and optionally getStaticPaths (for dynamic routes).

Example:

// pages/blog/[slug].js

export async function getStaticPaths() {
  const posts = await fetchPosts();
  return {
    paths: posts.map(post => ({ params: { slug: post.slug } })),
    fallback: 'blocking',
  };
}

export async function getStaticProps({ params }) {
  const post = await fetchPostBySlug(params.slug);
  return {
    props: { post },
    revalidate: 60, // (ISR) re-generates every 60 seconds
  };
}

Benefits:

  • Fast loading (cached on CDN)
  • Good for SEO
  • Scalable

20. What is the difference between SSR and CSR in Next.js?

Feature SSR (Server-Side Rendering) CSR (Client-Side Rendering)
Data Fetching On every request On client after page load
Performance Slower initial load (server-dependent) Faster initial HTML, but needs hydration
SEO Excellent Poor (initially no content for crawlers)
Use Case Authenticated pages, SEO-heavy pages Dashboards, real-time data, internal apps

SSR in Next.js:

export async function getServerSideProps(context) {
  const res = await fetch('<https://api.example.com/data>');
  const data = await res.json();

  return {
    props: { data },
  };
}

CSR in Next.js:

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?.name}</div>;
}

16. How do you handle authentication in Next.js?


You can implement authentication in multiple ways:

✅ Client-side authentication:


  • Store tokens in cookies/localStorage.
  • Use middleware or route guards for protected pages.
  • Example: JWT stored in HttpOnly cookies.

✅ Server-side authentication (recommended for SSR):


  • In getServerSideProps, check for a valid session or token.
  • Redirect if unauthenticated.

✅ Libraries:


  • next-auth for social login and email/password auth.
  • iron-session for encrypted session cookies.

17. What is the difference between Server Components and Client Components in Next.js App Router?


Feature Server Component Client Component
Runs on Server only Browser
Access to backend ✅ Yes ❌ No
Use state/hooks ❌ No ✅ Yes
Performance Faster, lighter Heavier due to hydration
Syntax Default in app/ folder Must add 'use client' at the top

18. What is Dynamic Routing in Next.js?


Dynamic routing allows pages to be created for dynamic URLs using square brackets.

Example:

bash
CopyEdit
pages/product/[id].js → /product/123

Inside the page:

js
CopyEdit
import { useRouter } from 'next/router'

const Product = () => {
  const router = useRouter()
  const { id } = router.query
  return <div>Product ID: {id}</div>
}


19. How do you handle form submissions in Next.js?


✅ Client-side:


  • Use fetch or axios to POST data to an API route.
js
CopyEdit
await fetch('/api/contact', {
  method: 'POST',
  body: JSON.stringify({ name, email }),
  headers: { 'Content-Type': 'application/json' }
})

✅ Server-side (API route):


js
CopyEdit
export default function handler(req, res) {
  const { name, email } = req.body
  // Validate & store
  res.status(200).json({ success: true })
}


20. How do you handle internationalization (i18n) in Next.js?


Next.js has built-in i18n support in next.config.js:

js
CopyEdit
i18n: {
  locales: ['en', 'fr', 'de'],
  defaultLocale: 'en',
}

You can also use:

  • next-translate
  • react-intl
  • i18next

URL-based routing for each locale is automatic:

/en/about, /fr/about, etc.


21. How do you use static assets like images or files in Next.js?


Put static files in the public/ directory.

Example:

html
CopyEdit
<img src="/logo.png" />

No need to import; the path is relative to the root (/).


22. What is prefetching in Next.js?


Next.js automatically prefetches pages linked with <Link> when they appear in the viewport. This improves performance.

Example:

js
CopyEdit
import Link from 'next/link'

<Link href="/about">About</Link>

This preloads the /about page JavaScript behind the scenes.


23. How do you handle error pages in Next.js?


  • 404 Page → Create pages/404.js
  • 500 Page → Create pages/500.js
  • Custom error handling for API routes using try/catch and proper HTTP status codes.

In App Router (Next.js 13+), use:

  • error.js file in a route folder for custom error UI.

24. What is next.config.js used for?


It configures your Next.js app globally. You can define:

  • Custom webpack config
  • Environment variables
  • i18n settings
  • Image domains
  • URL redirects and rewrites
  • Experimental features

Example:

js
CopyEdit
module.exports = {
  reactStrictMode: true,
  images: {
    domains: ['example.com'],
  },
}


25. What is the difference between Link and a tag in Next.js?


  • <Link> is used for client-side navigation without full page reload.
  • <a> causes a full page refresh.

Correct usage:

jsx
CopyEdit
import Link from 'next/link'

<Link href="/about">
  <a>About</a>
</Link>

In Next.js 13+ (App Router), just use:

jsx
CopyEdit
<Link href="/about">About</Link>



Comments

Popular posts from this blog

Download Kiran Publication Math Book PDF for SSC, Railway, and Banking Exams

Careerwill Gagan Pratap Sir Maths Book Pdf

THREE.RGBELoader is not a constructor: error solved

Contact form

Name

Email *

Message *