Next.js Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. What is colocation in the App Router?

    Correct answer: Keeping components and utilities next to routes inside app/

    Files in app/ become public only through page or route. So it's safe to keep a route's components, hooks, styles and tests next to its page.tsx. For clarity, use private _components folders or keep shared code in src/ outside app.

  2. 2. What is Next.js?

    Correct answer: A React framework with routing, server rendering and optimizations

    Next.js is built on React and adds what the library lacks: file-based routing, server and static rendering, Server Components and Server Functions, image and font optimization, building and deployment. Components are written in plain React.

  3. 3. How do you create a page at /about in the App Router?

    Correct answer: Create app/about/page.tsx with a default-exported component

    A route is defined by a folder, and a page.tsx (or .js) file makes it a public page. Without page, the folder isn't reachable by URL - you can keep components in it (colocation). There's no route configuration in next.config. A pages/about.tsx file is the old Pages Router convention.

  4. 4. How does layout.tsx differ from page.tsx?

    Correct answer: A layout wraps pages and preserves state during navigation

    A layout receives children and holds UI shared by nested routes (header, sidebar). When navigating between child pages, the layout doesn't remount: its state and DOM are preserved, and only the changed part renders. Both layout and page are Server Components by default.

  5. 5. What must the root app/layout.tsx contain?

    Correct answer: The <html> and <body> tags

    The root layout replaces _app and _document from the Pages Router and must render <html> and <body> itself. Metadata is set via the metadata or generateMetadata export, not next/head. Next.js has no mandatory provider.

  6. 6. How do you create a dynamic route /blog/:slug?

    Correct answer: The folder app/blog/[slug]/page.tsx

    A dynamic segment is a folder name in square brackets. The value arrives in params. [...slug] catches several segments; [[...slug]] does the same but also matches the route without segments. Colons and curly braces are other routers' syntax.

  7. 7. How do you correctly read params in a Next.js 16 page?

    Correct answer: const { slug } = await params - it's a Promise

    Since Next.js 15, params and searchParams are promises, and Next.js 16 removed synchronous access entirely. In a server component you await them; in a client page, use use(params). The useParams hook works only in client components.

  8. 8. Why is <Link> from next/link better than a plain <a href> for internal navigation?

    Correct answer: Navigation without a full page reload, plus route prefetching

    <Link> renders a regular <a> (so SEO doesn't suffer) but intercepts the click and performs an SPA transition: shared layouts are kept, and only what's needed is loaded. Links in the viewport are prefetched in production. For external addresses, use a plain <a>.

  9. 9. What kind of components are files in the app/ folder by default?

    Correct answer: Server Components

    In the App Router, everything is a Server Component by default: the code runs on the server and doesn't end up in the client bundle. To use state, effects, event handlers or browser APIs, add 'use client' at the top of the file.

  10. 10. A component uses useState and onClick but crashes with an error. What's missing?

    Correct answer: The 'use client' directive at the top of the file

    State hooks and event handlers work only in client components. 'use client' declares the boundary of the client part. Best practice is to move interactivity into small client components and keep the page itself on the server.

  11. 11. What is the loading.tsx file for?

    Correct answer: An instant segment fallback: Next.js wraps the page in <Suspense>

    Next.js automatically wraps page (and nested segments) in <Suspense fallback={<Loading />}>. The user immediately sees the layout and a skeleton, while content streams in when ready. For finer control, place your own <Suspense> inside the page.

  12. 12. Why must error.tsx be a client component?

    Correct answer: It's a React error boundary, which only works on the client

    error.tsx wraps the segment in an error boundary - a client-side mechanism. The component receives error and a retry() function that reloads and re-renders the segment (there's also reset() - re-render without refetching data). Errors in the root layout are caught by global-error.tsx.

  13. 13. How do you show a 404 page for a nonexistent product in a server page?

    Correct answer: Call notFound() from next/navigation

    notFound() stops rendering, shows the nearest not-found.tsx (or the default 404) and sets the appropriate status. A component can't return an HTTP status, and a regular error goes to error.tsx.

  14. 14. How do you set a page's title and description in the App Router?

    Correct answer: Export metadata or generateMetadata from a page/layout

    The Metadata API works in server components: export const metadata = { title, description }, and for dynamic values export async function generateMetadata({ params }). Values from layout and page are merged. next/head is a Pages Router API.

  15. 15. At what URL is the file public/logo.png served?

    Correct answer: /logo.png

    The contents of public are served from the site root. Favicons, robots.txt and static images go there. These files don't go through the build and don't get a hash in their name, so caching must be configured separately. /_next/static is the path for build-generated assets.

  16. 16. How do you create a GET /api/users API endpoint in the App Router?

    Correct answer: A file app/api/users/route.ts exporting a GET function

    Route Handlers use the Web Request/Response APIs: export async function GET(request: Request) { return Response.json(users) }. POST, PUT, PATCH, DELETE and others are supported. A folder can't contain both route.ts and page.tsx.

  17. 17. Which environment variables are available in browser code?

    Correct answer: Only those prefixed with NEXT_PUBLIC_, inlined at build time

    Next.js substitutes process.env.NEXT_PUBLIC_* into client code at build time, so changing a value requires a rebuild. Other variables are available only on the server - that way secrets (API keys, DB passwords) don't leak to the browser.

  18. 18. What does the <Image> component from next/image give you?

    Correct answer: Size and format selection, lazy loading, no CLS

    next/image generates srcset, serves modern formats (WebP/AVIF), lazy-loads by default and reserves space thanks to width/height (or fill), preventing layout shifts. For the LCP image, use preload (formerly priority).

  19. 19. Why does <Image src="https://cdn.example.com/a.jpg" ... /> produce a configuration error?

    Correct answer: External domains must be allowed in images.remotePatterns in next.config

    The image optimizer runs on your server, and without restrictions it could be used as a proxy for any URL. That's why allowed sources are listed in remotePatterns (protocol, host, path).

  20. 20. What does next/font do?

    Correct answer: Downloads the font at build time and serves it from your domain

    Fonts (Google or local) are downloaded at build time and served with your static assets: the browser doesn't contact Google, which is better for privacy and speed. Next.js also configures a fallback font with adjusted metrics to reduce CLS.

  21. 21. Where do you import useRouter from in the App Router?

    Correct answer: next/navigation

    In the App Router, navigation hooks - useRouter, usePathname, useSearchParams, useParams - are imported from next/navigation and work in client components. next/router is the Pages Router API. For a server-side redirect, use redirect().

  22. 22. How do you get the current path in a client component, e.g. to highlight the active link?

    Correct answer: usePathname()

    usePathname() returns the path and updates on client-side navigation. Reading window during render breaks SSR and hydration. The pathname property on useRouter existed in the Pages Router; it isn't in next/navigation.

  23. 23. How does SSR differ from SSG?

    Correct answer: SSR - HTML on every request, SSG - ahead of time at build

    Static Site Generation (prerendering) creates HTML at build time and serves it from a CDN - fast and cheap, but the data is "frozen". Server-Side Rendering produces HTML on every request - the data is fresh and personalized, but load and TTFB are higher. Rendering in the browser is CSR.

  24. 24. What is ISR (Incremental Static Regeneration)?

    Correct answer: Background updating of static pages without a full rebuild

    Users get a cached static page, and after the period expires (or revalidatePath/revalidateTag is called), Next.js regenerates it in the background and updates the cache. It's a compromise between the speed of SSG and the freshness of SSR.

  25. 25. When does getServerSideProps run in the Pages Router?

    Correct answer: On the server on every request

    getServerSideProps is SSR in the Pages Router: the function receives the request context (cookies, query) and returns props. At build time, getStaticProps runs instead. In the App Router, both APIs are replaced by async server components.

  26. 26. What does getStaticPaths do in the Pages Router?

    Correct answer: Returns the paths of a dynamic route to build

    For a pages/posts/[id].tsx page with getStaticProps, Next.js needs to know which ids to build ahead of time. The fallback option defines behavior for other paths. The App Router counterpart is generateStaticParams.

  27. 27. What does a folder in parentheses do, e.g. app/(marketing)/about/page.tsx?

    Correct answer: Groups routes without affecting the URL - the page is at /about

    Route groups organize code and let a group have its own layout (e.g. separate ones for marketing and the user dashboard) without changing URLs. You can even have several root layouts in different groups.

  28. 28. Why give a folder a name with an underscore, e.g. app/_components?

    Correct answer: It's a private folder: it and its files are excluded from routing

    Private folders explicitly separate helper code from routes. Strictly speaking, files without page/route aren't public anyway, but _ protects against accidentally creating a route and makes the structure clearer.

  29. 29. Which route will catch /docs/a/b/c?

    Correct answer: app/docs/[...slug]/page.tsx

    A catch-all segment [...slug] collects all following segments into an array. A regular [slug] matches exactly one segment. An optional catch-all [[...slug]] also matches /docs itself. Next.js doesn't support asterisks in folder names.

  30. 30. What do the next build and next start commands do?

    Correct answer: build creates the production build, start runs it

    next dev is the development server with fast refresh. next build compiles the app, prerenders static routes and prints a report. next start runs the production server on the build output. For a static site there's output: 'export'.

  31. 31. Which bundler does Next.js 16 use by default for next dev and next build?

    Correct answer: Turbopack, without extra flags

    Since Next.js 16, Turbopack is stable and used by default in both modes - the --turbopack flag is no longer needed. You can go back to Webpack with the --webpack flag. If the project has a custom webpack config, next build without the flag fails so that the config isn't silently ignored.

  32. 32. In Next.js 16, what is the file formerly called middleware.ts named?

    Correct answer: proxy.ts

    The middleware convention is deprecated and renamed to proxy to emphasize its role at the network boundary (redirects, rewrites, headers). The exported function is also called proxy. Proxy runs in the Node.js runtime; the edge runtime isn't supported there.

  33. 33. How do you redirect the user to /login from a server component?

    Correct answer: Call redirect('/login') from next/navigation

    redirect() works in server components, Server Functions and Route Handlers. It throws a special exception, so code after it doesn't run, and you must not wrap it in try/catch. useRouter is available only in client components, and <Navigate> is from React Router.

  34. 34. How do you get the ?page=2 query parameter in a server page?

    Correct answer: From the searchParams prop, which you await

    The page receives searchParams as a promise. Reading the query makes the page dynamic, because the values are known only at request time. In client components, use useSearchParams(). params contains only the dynamic path segments.

  35. 35. How do you load data in a server component?

    Correct answer: Make the component async and call await fetch() or a DB query

    Server components can be async and access data directly - APIs, ORMs, the file system - without sending secrets to the browser. Calling your own Route Handler from a server component is an unnecessary network round trip. Hooks aren't available in server components.

  36. 36. Where do you import global CSS in the App Router?

    Correct answer: In the root app/layout.tsx via import

    Global styles are imported in the root layout and apply to all routes. For component styles, use CSS Modules (*.module.css), Tailwind or CSS-in-JS with RSC support. Next.js has no index.html file.

  37. 37. Where does a console.log from a server component appear?

    Correct answer: In the terminal where the Next.js server is running

    A server component runs on the server (or at build time), so its logs go to the Node.js process output. In development, Next.js may mirror server logs to the browser for convenience, but the code still runs on the server.

  38. 38. What do you pass to <Image> for an image that stretches over the whole parent block?

    Correct answer: The fill prop, with position: relative on the parent

    When dimensions aren't known in advance, use fill: the image is absolutely positioned and fills the parent, which must be relative, absolute or fixed. sizes hints how wide the image will be so the browser doesn't download a file that's too large. Fitting is controlled with object-fit.

  39. 39. How do you lazy-load a heavy client component in Next.js?

    Correct answer: With next/dynamic (or React.lazy + Suspense)

    const Chart = dynamic(() => import('./Chart')) moves the code into a separate chunk and lets you specify loading. The ssr: false option disables server rendering but can be used only in client components. Server components don't end up in the bundle anyway.

  40. 40. Why load third-party scripts via next/script?

    Correct answer: You can choose a loading strategy (afterInteractive, lazyOnload, etc.)

    The <Script> component lets you avoid blocking page load with analytics and widgets: beforeInteractive for critical scripts, afterInteractive (the default) and lazyOnload for secondary ones. A script loads once even when navigating between pages.

  41. 41. How do you build a Next.js app into a set of static files without a Node.js server?

    Correct answer: Set output: 'export' in next.config

    A static export puts HTML, CSS and JS into the out folder, which you can host on any static hosting. Limitations: features that need a server don't work - cookies(), dynamic Route Handlers, ISR, default image optimization, Server Functions.

  42. 42. What happens if app/dashboard/ contains both page.tsx and route.ts?

    Correct answer: A build error: these files conflict over the same URL

    Both files claim the same URL, and Next.js reports a conflict. API routes are usually moved into a separate branch, e.g. app/api/....

  43. 43. How does template.tsx differ from layout.tsx?

    Correct answer: A template remounts on every navigation, a layout persists

    A template wraps pages like a layout but gets a unique key on each navigation: state resets and effects run again. This is useful, for example, for enter animations or logging page views. In most cases a layout is enough.

  44. 44. Can you use the useState and useEffect hooks in a server component?

    Correct answer: No: server components have no state or effects

    A server component runs once to produce a result and doesn't "live" afterwards. State, effects and event handlers are client features. A server component can render a client component and pass it data via props.

  45. 45. When does <Link> prefetch a route?

    Correct answer: When the link enters the viewport (in production)

    Prefetching makes navigation instant. It's disabled in dev mode, so check navigation speed on a production build. The behavior is configured with the prefetch prop (false, true, 'auto'). In Next.js 16 prefetching became incremental: shared layouts are downloaded once.

  46. 46. Will state in a sidebar inside a shared layout survive navigation between pages?

    Correct answer: Yes: a shared layout doesn't remount during navigation

    Next.js renders only the changed segments, while shared layouts stay mounted: typed text, open menus and scroll position are preserved. If you need a reset on navigation, use template.tsx or key.

  47. 47. How do you type the props of app/blog/[slug]/page.tsx in Next.js 16?

    Correct answer: With the global helper PageProps<'/blog/[slug]'>

    Next.js generates route types (during next dev, next build or next typegen), and the PageProps, LayoutProps and RouteContext helpers know the params shape for each path. NextPage is a Pages Router type.

  48. 48. What is the minimum Node.js version required for Next.js 16?

    Correct answer: 20.9

    Next.js 16 requires Node.js 20.9+ (LTS); Node.js 18 support was dropped. Requirements for TypeScript (5.1+) and browsers (Chrome/Edge/Firefox 111+, Safari 16.4+) also went up.

  49. 49. Can you use CSS Modules in Next.js without extra configuration?

    Correct answer: Yes: *.module.css files are supported out of the box

    import styles from './Button.module.css' and className={styles.primary} - class names become locally scoped. Sass (after installing the sass package), Tailwind and global CSS are supported too.

  50. 50. What title does the page get with export const metadata = { title: 'Profile' } in the page and title: { template: '%s | Shop', default: 'Shop' } in the layout?

    Correct answer: Profile | Shop

    title.template from the layout is applied to titles of child segments: %s is replaced with the page's title. default is used if a child segment doesn't set a title. This saves you from repeating the site name on every page.

  51. 51. How does a client component read the [slug] segment of the current URL?

    'use client'
    import { useParams } from 'next/navigation'
    
    export function ShareButton() {
      const { slug } = useParams<{ slug: string }>()
    }

    Correct answer: With the useParams hook from next/navigation

    Pages and layouts get params as a prop (a Promise in Next.js 16), while deeply nested client components can call useParams() instead of receiving params through props.

  52. 52. How do you generate sitemap.xml in the App Router?

    // app/sitemap.ts
    import type { MetadataRoute } from 'next'
    
    export default function sitemap(): MetadataRoute.Sitemap {
      return [{ url: 'https://acme.com', lastModified: new Date() }]
    }

    Correct answer: Add app/sitemap.ts that returns the list of URLs

    sitemap is a special metadata file. Next.js serves it at /sitemap.xml; the function can fetch URLs from a database or CMS.

  53. 53. Which file controls the /robots.txt response?

    Correct answer: app/robots.ts or a static app/robots.txt

    robots.ts returns an object of type MetadataRoute.Robots with rules and an optional sitemap URL, so you can vary rules per environment.

  54. 54. How do you set the site favicon in the App Router?

    Correct answer: Place favicon.ico in the app/ folder

    Icon files are metadata file conventions. icon and apple-icon can also be generated in code with icon.tsx.

  55. 55. How does permanentRedirect() differ from redirect()?

    Correct answer: permanentRedirect returns 308, redirect returns 307

    Use a permanent redirect when a URL has moved for good (e.g. a renamed slug), so search engines transfer ranking to the new address.

  56. 56. How do you redirect the old /blog/:slug URLs to /news/:slug for every request, without code in pages?

    // next.config.ts
    async redirects() {
      return [{ source: '/blog/:slug', destination: '/news/:slug', permanent: true }]
    }

    Correct answer: With redirects() in next.config.ts

    Config redirects run before the filesystem routes are matched. For many dynamic redirects (e.g. from a database), use proxy.ts instead.

  57. 57. What happened to the next lint command in Next.js 16?

    Correct answer: It was removed - run ESLint or Biome directly

    next build also no longer runs the linter. eslint-config-next uses the flat config format.

  58. 58. Can the app/ folder live inside src/?

    Correct answer: Yes - src/app works; config files stay at the root

    The src folder separates application code from config files. If app/ exists at the root too, the root one wins and src/app is ignored.

  59. 59. When should you use router.push() instead of <Link>?

    Correct answer: For navigation in code, e.g. after a form saves

    <Link> renders a real <a>, supports prefetching and opening in a new tab. Use useRouter only when there is no clickable link to render.

  60. 60. What does the replace prop do on <Link>?

    <Link href="/step-2" replace>Next</Link>

    Correct answer: Replaces the current history entry instead of adding a new one

    With replace, the browser's Back button skips the replaced page - handy for wizards or tab filters that shouldn't fill the history.

  61. 61. What does scroll={false} on <Link> do?

    Correct answer: Keeps the current scroll position on navigation

    By default Next.js scrolls to the top of the new segment if it isn't visible. Disable it, e.g., for tabs that only change part of the page.

  62. 62. What is the useLinkStatus hook for?

    function Hint() {
      const { pending } = useLinkStatus()
      return <span className={pending ? 'spinner' : ''} />
    }

    Correct answer: Showing inline pending feedback inside a <Link>

    It must be used in a descendant of <Link>. Prefer loading.tsx and prefetching for instant navigations; the hook is a patch for slow transitions.

  63. 63. How do you handle POST /api/posts in a Route Handler?

    // app/api/posts/route.ts
    export async function POST(request: Request) {
      const body = await request.json()
      return Response.json(body, { status: 201 })
    }

    Correct answer: Export an async function named POST from route.ts

    Each HTTP method is a named export: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS. Unsupported methods get a 405 response.

  64. 64. Is the alt prop required on next/image?

    Correct answer: Yes - use alt="" for decorative images

    alt is a required prop of <Image>. An empty string tells assistive technology to skip a decorative image.

  65. 65. Which .env file is meant for local secrets and should not be committed?

    Correct answer: .env.local

    .env.local overrides the defaults from .env and is normally in .gitignore. .env and .env.production hold non-secret defaults that can be committed.

  66. 66. Why does export const metadata in a 'use client' page cause an error?

    Correct answer: Metadata exports are supported only in server components

    Keep the page a server component and move interactive parts into a separate client component, or set the title in a parent layout.

  67. 67. Which pages does app/dashboard/layout.tsx wrap?

    Correct answer: All pages under /dashboard, nested ones too

    Layouts nest: the root layout wraps the dashboard layout, which wraps every page below it. Nested segments can add their own layouts.

  68. 68. Where do you set themeColor in Next.js 16?

    export const viewport = { themeColor: '#0f172a' }

    Correct answer: In the viewport export, not in metadata

    Viewport-related fields (themeColor, colorScheme, width) moved out of metadata into a separate viewport export.

  69. 69. How do you add a web app manifest for a PWA?

    Correct answer: Add app/manifest.ts or a static manifest.json

    manifest.ts returns MetadataRoute.Manifest with the name, icons and colors, and Next.js adds the <link rel="manifest"> tag.

  70. 70. Do you need 'use client' at the top of every client component file?

    Correct answer: No - only at the boundary of the client tree

    'use client' marks the entry point from server to client. Adding it everywhere isn't harmful but makes it harder to see where the boundary is.

  71. 71. How do you add JSON-LD structured data to a page?

    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
    />

    Correct answer: Render a <script type="application/ld+json"> in the page

    Escaping < prevents XSS through the injected JSON. Types from schema-dts help keep the data valid.

  72. 72. How does a server component read a request header like user-agent?

    import { headers } from 'next/headers'
    
    const ua = (await headers()).get('user-agent')

    Correct answer: Await headers() from next/headers, then .get()

    headers() is async in Next.js 16 and returns read-only headers. Using it makes the route render at request time.

  73. 73. What does export const dynamicParams = false do on a page with generateStaticParams (without Cache Components)?

    Correct answer: Params outside generateStaticParams return a 404

    By default unknown params are rendered on demand and cached. dynamicParams is not available when Cache Components are enabled.

  74. 74. How do you serve the whole app under /docs (e.g. acme.com/docs)?

    Correct answer: Set basePath: '/docs' in next.config.ts

    basePath is applied automatically to <Link> and router.push. It's set at build time and can't change without rebuilding.

  75. 75. Which next/script strategy loads a script during browser idle time, e.g. a chat widget?

    Correct answer: lazyOnload

    afterInteractive (the default) loads right after hydration starts; beforeInteractive is for critical scripts before any Next.js code. Low-priority widgets fit lazyOnload.