HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
50 Topics
Chapter•300 Minutes

Optional - Pages Router Comprehensive Interview Question Bank

50 progressive interview questions focusing exclusively on the Next.js Pages Router directory, lifecycle methods, data fetching strategies, custom configurations, and migration paths.

Q1: How does file-based routing work in the Pages Router?

In the Pages Router, every file inside the pages/ directory automatically maps to a public URL route based on its filename. Files like pages/index.js map to /, pages/about.js maps to /about, and nested directories like pages/blog/first-post.js map to /blog/first-post.

Basic Pages Route Definition
// pages/contact.js -> Maps to /contact
export default function Contact() {
  return <h1>Contact Us</h1>;
}
💡 Exporting a React component as default from a file in pages/ instantly registers the route.
Key Takeaways
  • Files inside pages/ directly map to URL endpoints.
  • index.js serves as the root file for any directory.
Knowledge Check

What is the corresponding URL for a file located at pages/dashboard/settings.js?

Q2: What is getStaticProps and when should you use it?

getStaticProps is an async function that runs exclusively on the server at build time. It fetches data required to pre-render static HTML pages (SSG). Use it for pages with data that doesn't change on every user request, such as marketing pages, blogs, or documentation.

SSG Data Fetching with getStaticProps
// pages/posts.js
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  return {
    props: { posts }, // Passed to the page component
  };
}

export default function Posts({ posts }) {
  return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}
💡 getStaticProps fetches data at build time and supplies it as props to the page component.
Key Takeaways
  • Runs only on the server during next build.
  • Passes fetched data as props to the default exported page component.
Knowledge Check

Where does getStaticProps execute when a user visits the site in production?

Q3: What is getServerSideProps and how does it differ from getStaticProps?

getServerSideProps executes on every incoming request on the server. Unlike getStaticProps (which builds once), it fetches fresh data per request before rendering HTML. Use it when data must be computed at request time (e.g., user-specific dashboards or dynamic search queries).

SSR Data Fetching with getServerSideProps
// pages/profile.js
export async function getServerSideProps(context) {
  const { req, res } = context;
  const user = await fetchUserFromSession(req);

  return {
    props: { user },
  };
}
💡 getServerSideProps receives request context (req, res, query) and computes fresh props per request.
Key Takeaways
  • Runs on every HTTP request on the server.
  • Slower initial TTFB compared to getStaticProps because HTML is built per request.
Knowledge Check

Which parameter object does getServerSideProps receive to access request headers and cookies?

Q4: How does getStaticPaths work alongside getStaticProps for dynamic routes?

When using dynamic routes (e.g., pages/posts/[id].js) with getStaticProps, getStaticPaths defines the list of path instances that must be pre-rendered to static HTML during build time.

Defining Static Path Instances
// pages/posts/[id].js
export async function getStaticPaths() {
  return {
    paths: [
      { params: { id: '1' } },
      { params: { id: '2' } }
    ],
    fallback: false,
  };
}
💡 Returns an array of path parameter objects that Next.js will pre-render statically during build.
Key Takeaways
  • Defines which dynamic parameter paths to pre-render at build time.
  • Must be paired with getStaticProps on dynamic routes.
Knowledge Check

Which function MUST be used alongside getStaticProps on dynamic routes like pages/blog/[slug].js?

Q5: What are the differences between fallback: false, fallback: true, and fallback: 'blocking'?

  • fallback: false: Ungenerated paths return a 404 page.
  • fallback: true: Serves a fallback page (router.isFallback) instantly, fetches data in the background, then swaps in content.
  • fallback: 'blocking': SSRs the new page on the first request, pausing navigation until HTML is rendered, then caches it for future visits.
Key Takeaways
  • false: Strict 404 for missing paths.
  • true: Shows fallback UI while generating in background.
  • blocking: Server-renders on demand before sending response (no fallback spinner).
Knowledge Check

Which fallback setting blocks initial page delivery until full HTML is generated on the server for uncached paths?

Q6: How does Incremental Static Regeneration (ISR) work in the Pages Router?

ISR allows static pages to be updated in the background without re-building the entire site. By adding a revalidate property (in seconds) to getStaticProps, Next.js regenerates the page in the background when requests come in after the timer expires.

ISR Configuration in getStaticProps
export async function getStaticProps() {
  const data = await fetchData();
  return {
    props: { data },
    revalidate: 60, // Next.js will attempt revalidation every 60 seconds
  };
}
💡 Setting revalidate: 60 ensures static HTML updates in the background when requested after 60 seconds.
Key Takeaways
  • Enable by returning revalidate: <seconds> in getStaticProps.
  • Combines static page performance with periodic dynamic updates.
Knowledge Check

What happens when a user requests an ISR page 120 seconds after build time if revalidate is set to 60?

Q7: What is getInitialProps and why is it generally discouraged in modern Pages Router apps?

getInitialProps was the original data fetching method in Next.js. It runs on both server (initial load) and client (route transitions). Disadvantage: using getInitialProps in _app.js disables Automatic Static Optimization for the entire application.

Key Takeaways
  • Executes on server during initial load and on client during navigation.
  • Disables global Automatic Static Optimization if placed in _app.js.
Knowledge Check

What is the main side effect of defining getInitialProps inside pages/_app.js?

Q8: What is pages/_app.js used for in the Pages Router?

pages/_app.js initializes all pages. Use it to persist layouts across page changes, inject global CSS, maintain state across navigations (e.g., Redux or React Context providers), and handle global error tracking.

Custom _app.js Implementation
// pages/_app.js
import '../styles/globals.css';

export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}
💡 Component represents the active page; pageProps contains pre-fetched props from data methods.
Key Takeaways
  • Wraps every page component in the application.
  • Used for importing global CSS and configuring context providers.
Knowledge Check

Which prop in pages/_app.js represents the current active page component being rendered?

Q9: What is pages/_document.js and how does it differ from pages/_app.js?

_document.js customizes the raw HTML document structure (<html>, <head>, <body>). It executes only on the server during initial rendering (never on the client). Do not use it for application state or event handlers.

Custom _document.js Structure
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
💡 Main renders active page markup; NextScript injects framework JavaScript scripts.
Key Takeaways
  • Customizes top-level <html>, <Head>, and <body> tags.
  • Executes strictly on the server; cannot attach client event listeners or React state.
Knowledge Check

Can you use React hooks like useState() inside pages/_document.js?

Q10: What is Automatic Static Optimization in the Pages Router?

Next.js automatically determines if a page can be rendered statically. If a page has no blocking data fetching methods (getServerSideProps or getInitialProps), Next.js pre-renders the page to static HTML at build time automatically.

Key Takeaways
  • Opt-in by omitting server-side data fetching functions.
  • Generates static HTML files for maximum CDN performance.
Knowledge Check

How do you enable Automatic Static Optimization for a page file inside pages/?