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/?

Q11: How do single dynamic routes work in pages/[id].js?

Square bracket syntax [id].js creates a dynamic route segment. The parameter value is extracted in getServerSideProps / getStaticProps via context.params.id, or on the client using useRouter().query.id.

Accessing Dynamic Route Params
// pages/user/[id].js
import { useRouter } from 'next/router';

export default function User() {
  const router = useRouter();
  const { id } = router.query;
  return <p>User ID: {id}</p>;
}

useRouter().query extracts dynamic parameters from the URL.

Key Takeaways
  • Folder/file names like [param].js match dynamic path segments.

  • Access dynamic values via context.params or useRouter().query.

Knowledge Check

In pages/products/[category].js, how do you read 'category' inside getServerSideProps?

Q12: What are Catch-all routes [...slug].js in the Pages Router?

Catch-all routes using [...slug].js match multiple nested URL path segments. For example, pages/post/[...slug].js matches /post/a, /post/a/b, and /post/a/b/c. Query parameters return slug as an array of path segments (['a', 'b', 'c']).

Key Takeaways
  • Syntax: [...slug].js matches multiple URL path segments.

  • Extracted as an array of string segments.

Knowledge Check

For the file pages/docs/[...slug].js, what value does router.query.slug hold when visiting /docs/api/v1/users?

Q13: How do Optional Catch-all routes [[...slug]].js work?

Optional catch-all routes using double brackets [[...slug]].js match dynamic nested segments AND the base route without parameters (/docs, /docs/a, /docs/a/b). On the base path /docs, slug is undefined.

Key Takeaways
  • Matches target base paths alongside nested sub-routes.

  • Prevents creating a separate index.js file for root paths.

Knowledge Check

What is router.query.slug for pages/shop/[[...slug]].js when navigating to /shop?

Q14: What are API Routes in pages/api/ and how are they created?

Files inside pages/api/ map to HTTP API endpoints rather than HTML pages. They export a default request handler function function handler(req, res) that runs on Node.js server runtimes.

Basic API Route Handler
// pages/api/hello.js -> Maps to /api/hello
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello World' });
}

Default exported handler manages incoming requests to the /api/hello endpoint.

Key Takeaways
  • Files in pages/api/ serve JSON/data responses instead of HTML UI.

  • Handler functions receive standard Node.js req and res objects.

Knowledge Check

Do files inside pages/api/ generate frontend React HTML component outputs?

Q15: How do you use Node.js middleware in Pages Router API routes?

API handlers can execute standard Express/Connect middleware helper functions or custom wrapper functions to inspect request headers, authenticate tokens, or log requests before returning data.

API Middleware Wrapper Pattern
function withAuth(handler) {
  return async (req, res) => {
    if (!req.headers.authorization) {
      return res.status(401).json({ error: 'Unauthorized' });
    }
    return handler(req, res);
  };
}

export default withAuth(function handler(req, res) {
  res.status(200).json({ data: 'Secret Data' });
});

Wrapper functions execute authentication logic prior to calling core request handlers.

Key Takeaways
  • Wrap API handlers or use helper functions to integrate custom middleware.

  • Runs within standard Node.js server contexts.

Knowledge Check

Where does custom API route middleware execute in the Pages Router?

Q16: How do custom 404 and 500 error pages work in the Pages Router?

  • pages/404.js: Static error page rendered at build time for missing routes.
  • pages/500.js: Server error page pre-rendered or computed when server exceptions occur.
Custom 404 Page Definition
// pages/404.js
export default function Custom404() {
  return <h1>404 - Page Not Found</h1>;
}

Next.js builds pages/404.js statically to serve instantly on missing route queries.

Key Takeaways
  • pages/404.js is statically pre-rendered at build time.

  • pages/500.js handles unhandled server errors.

Knowledge Check

Is pages/404.js built as static HTML or dynamic SSR by default?

Q17: How does next/head manage document metadata in the Pages Router?

The <Head> component from next/head allows appending metadata tags (<title>, <meta>, <link>) to the HTML <head> section from individual page files.

Adding Page Metadata with next/head
import Head from 'next/head';

export default function About() {
  return (
    <div>
      <Head>
        <title>About Us | My Company</title>
        <meta name="description" content="Learn about our mission" key="desc" />
      </Head>
      <p>About Page Content</p>
    </div>
  );
}

next/head hoists title and description tags into the document head region.

Key Takeaways
  • Injects HTML head metadata from page components.

  • Use the key attribute to prevent duplicate meta tag rendering.

Knowledge Check

Why should you add a key attribute to meta tags inside next/head?

Q18: How do you listen to route navigation events using useRouter?

router.events allows subscribing to route change events like routeChangeStart, routeChangeComplete, and routeChangeError. Commonly used to display global loading progress bars (e.g. NProgress).

Subscribing to Route Events
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function App({ Component, pageProps }) {
  const router = useRouter();
  useEffect(() => {
    const handleStart = (url) => console.log(`Navigating to: ${url}`);
    router.events.on('routeChangeStart', handleStart);
    return () => router.events.off('routeChangeStart', handleStart);
  }, [router]);
  return <Component {...pageProps} />;
}

Listens for navigation initialization and cleans up event handlers on unmount.

Key Takeaways
  • Subscribe via router.events.on(eventName, handler) inside useEffect.

  • Clean up listeners using router.events.off().

Knowledge Check

Which router event fires immediately when a client-side route transition is triggered?

Q19: What is Shallow Routing in the Pages Router?

Shallow routing allows changing the URL without re-running data fetching methods (getStaticProps, getServerSideProps). Call router.push('/page?query=1', undefined, { shallow: true }) to update state in the URL while preserving active page component state.

Executing Shallow Navigation
import { useRouter } from 'next/router';

export default function Page() {
  const router = useRouter();
  const updateFilter = (filter) => {
    router.push(`/search?filter=${filter}`, undefined, { shallow: true });
  };
  return <button onClick={() => updateFilter('active')}>Filter</button>;
}

Updates query parameter in the address bar without executing page data functions.

Key Takeaways
  • Updates URL query string without re-triggering server data methods.

  • Only works for URL changes inside the same page.

Knowledge Check

Does shallow routing prevent getStaticProps/getServerSideProps from re-executing when navigating to a DIFFERENT page file?

Q20: When and why would you use a Custom Server (server.js) with Pages Router?

A custom Node.js server (using Express or Fastify) was traditionally used to integrate custom backend routing or legacy HTTP proxies. Warning: Custom servers disable Automatic Static Optimization and cannot be deployed to serverless environments like Vercel.

Key Takeaways
  • Integrates custom Node.js frameworks (Express) with Next.js page rendering.

  • Disables Vercel serverless deployments and static optimization.

Knowledge Check

What primary feature is lost when using a custom Express server.js file with Next.js?

Q21: How do you trigger On-Demand ISR Revalidation in the Pages Router?

On-Demand Revalidation purges static cache files immediately via an API route without waiting for the revalidate timer to expire. Call res.revalidate('/target-page-path') inside an authenticated API route handler.

API Route Revalidation Handler
// pages/api/revalidate.js
export default async function handler(req, res) {
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' });
  }
  try {
    await res.revalidate('/posts/1');
    return res.json({ revalidated: true });
  } catch (err) {
    return res.status(500).send('Error revalidating');
  }
}

res.revalidate immediately rebuilds the target static page cache.

Key Takeaways
  • Purges static page cache instantly on content updates.

  • Triggered via res.revalidate('/path') inside API routes.

Knowledge Check

Which response method triggers On-Demand Revalidation inside a Pages Router API route?

Q22: How does next/dynamic perform code splitting in the Pages Router?

next/dynamic wraps standard import() calls to lazy-load React components, splitting them into separate JS chunks. Setting { ssr: false } skips server-side rendering for browser-only libraries.

Lazy Loading Component with next/dynamic
import dynamic from 'next/dynamic';

const HeavyChart = dynamic(() => import('../components/HeavyChart'), {
  ssr: false,
  loading: () => <p>Loading Chart...</p>,
});

export default function Dashboard() {
  return <HeavyChart />;
}

HeavyChart is split into an independent JS chunk and rendered exclusively on the client.

Key Takeaways
  • Reduces initial bundle size by lazy-loading components on demand.

  • Use { ssr: false } for browser-dependent modules.

Knowledge Check

What parameter setting in next/dynamic prevents a heavy client chart library from rendering on Node.js servers?

Q23: What was Preview Mode in the Pages Router and how was it enabled?

Preview Mode bypassed static pre-rendering (SSG) to fetch draft content from Headless CMSs. Enabled by an API route calling res.setPreviewData({}), which set preview cookies that forced getStaticProps to render dynamically at request time.

Key Takeaways
  • Bypasses SSG build cache to show unpublished draft content.

  • Enabled via res.setPreviewData({}) inside API routes.

Knowledge Check

How does Pages Router Preview Mode signal getStaticProps to render draft content dynamically?

Q24: How do you implement persistent Page-Level Layouts in the Pages Router?

Attach a custom .getLayout function property to individual page components. In pages/_app.js, execute Component.getLayout() to wrap active pages without unmounting shared layouts during navigation.

Page-Level Layout Setup
// pages/dashboard.js
export default function Dashboard() { return <h1>Dashboard</h1>; }
Dashboard.getLayout = function getLayout(page) {
  return <SidebarLayout>{page}</SidebarLayout>;
};

// pages/_app.js
export default function MyApp({ Component, pageProps }) {
  const getLayout = Component.getLayout || ((page) => page);
  return getLayout(<Component {...pageProps} />);
}

_app.js executes the page's getLayout function to maintain layout tree persistence.

Key Takeaways
  • Attaches custom .getLayout properties to page component functions.

  • Preserves component state and scroll position across page transitions.

Knowledge Check

What advantage does the getLayout pattern offer over wrapping page JSX directly in a layout component inside each file?

Q25: How do you extend Webpack configuration inside next.config.js for the Pages Router?

Custom Webpack configurations are defined inside the webpack property in next.config.js. It receives the existing config object and options (isServer, dev, webpack) to mutate or append plugins.

Extending Webpack in next.config.js
// next.config.js
module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.resolve.fallback.fs = false; // Fixes client-side fs module resolution
    }
    return config;
  },
};

Modifies resolution fallbacks to prevent bundling Node modules into client bundles.

Key Takeaways
  • Extend Webpack rules using next.config.js.

  • Check options.isServer to target server vs client bundle configurations.

Knowledge Check

Which flag inside next.config.js webpack options determines if Webpack is bundling server code?

Q26: What properties are available on the context parameter in getStaticProps?

The context parameter in getStaticProps provides keys: params (dynamic path parameters), preview (boolean for preview mode), previewData, locale, locales, and defaultLocale.

Key Takeaways
  • params contains dynamic URL route parameters.

  • Contains localization and preview mode metadata.

Knowledge Check

Is req (the HTTP Request object) available inside getStaticProps context?

Q27: What properties are available on the context parameter in getServerSideProps?

getServerSideProps context includes: req (HTTP IncomingMessage), res (HTTP ServerResponse), query (URL query string and path params), params, resolvedUrl, locale, locales, and defaultLocale.

Key Takeaways
  • Provides direct access to Node.js HTTP req and res objects.

  • query contains both query string parameters and path parameters.

Knowledge Check

Which object in getServerSideProps context allows reading client request cookies?

Q28: How does Internationalized (i18n) Routing work in the Pages Router?

Next.js provides built-in internationalized routing configured in next.config.js. Supports two strategies: Sub-path Routing (/en/blog, /fr/blog) and Domain Routing (example.com/blog, example.fr/blog).

i18n Configuration
// next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'es'],
    defaultLocale: 'en',
  },
};

Automatically handles sub-path localization routing across all pages.

Key Takeaways
  • Configure i18n object in next.config.js with locales and defaultLocale.

  • Access active locale via useRouter().locale or context.locale.

Knowledge Check

How do you access the active locale string inside getStaticProps?

Q29: How do you trigger server-side redirects inside getStaticProps or getServerSideProps?

Return a redirect object from getStaticProps or getServerSideProps containing destination (string) and permanent (boolean: true for 308, false for 307) or statusCode.

Server-Side Redirect in getServerSideProps
export async function getServerSideProps(context) {
  const session = await getSession(context.req);
  if (!session) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    };
  }
  return { props: { user: session.user } };
}

Unauthenticated requests are redirected server-side before page rendering occurs.

Key Takeaways
  • Return { redirect: { destination: '/login', permanent: false } }.

  • Halts page rendering and issues an immediate HTTP redirect response.

Knowledge Check

What status code is returned when setting permanent: false inside a server redirect object?

Q30: How do you return a 404 response from getStaticProps or getServerSideProps?

Return { notFound: true } from getStaticProps or getServerSideProps. Next.js immediately stops page rendering and serves the custom pages/404.js page with a 404 HTTP status code.

Returning 404 for Missing Database Records
export async function getStaticProps({ params }) {
  const post = await fetchPost(params.id);
  if (!post) {
    return { notFound: true }; // Triggers 404 page
  }
  return { props: { post } };
}

If fetchPost returns null, notFound: true renders the 404 error page.

Key Takeaways
  • Return { notFound: true } when target database items do not exist.

  • Renders the custom 404 error page automatically.

Knowledge Check

What happens when getStaticProps returns { notFound: true }?