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.
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 throughpageorroute. So it's safe to keep a route's components, hooks, styles and tests next to itspage.tsx. For clarity, use private_componentsfolders or keep shared code insrc/outsideapp.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. How do you create a page at
/aboutin the App Router?Correct answer: Create
app/about/page.tsxwith a default-exported componentA route is defined by a folder, and a
page.tsx(or.js) file makes it a public page. Withoutpage, the folder isn't reachable by URL - you can keep components in it (colocation). There's no route configuration innext.config. Apages/about.tsxfile is the old Pages Router convention.4. How does
layout.tsxdiffer frompage.tsx?Correct answer: A layout wraps pages and preserves state during navigation
A layout receives
childrenand 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. What must the root
app/layout.tsxcontain?Correct answer: The
<html>and<body>tagsThe root layout replaces
_appand_documentfrom the Pages Router and must render<html>and<body>itself. Metadata is set via themetadataorgenerateMetadataexport, notnext/head. Next.js has no mandatory provider.6. How do you create a dynamic route
/blog/:slug?Correct answer: The folder
app/blog/[slug]/page.tsxA 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. How do you correctly read
paramsin a Next.js 16 page?Correct answer:
const { slug } = await params- it's a PromiseSince Next.js 15,
paramsandsearchParamsare promises, and Next.js 16 removed synchronous access entirely. In a server component youawaitthem; in a client page, useuse(params). TheuseParamshook works only in client components.8. Why is
<Link>fromnext/linkbetter 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. 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. A component uses
useStateandonClickbut crashes with an error. What's missing?Correct answer: The
'use client'directive at the top of the fileState 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. What is the
loading.tsxfile 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. Why must
error.tsxbe a client component?Correct answer: It's a React error boundary, which only works on the client
error.tsxwraps the segment in an error boundary - a client-side mechanism. The component receiveserrorand aretry()function that reloads and re-renders the segment (there's alsoreset()- re-render without refetching data). Errors in the root layout are caught byglobal-error.tsx.13. How do you show a 404 page for a nonexistent product in a server page?
Correct answer: Call
notFound()fromnext/navigationnotFound()stops rendering, shows the nearestnot-found.tsx(or the default 404) and sets the appropriate status. A component can't return an HTTP status, and a regular error goes toerror.tsx.14. How do you set a page's title and description in the App Router?
Correct answer: Export
metadataorgenerateMetadatafrom a page/layoutThe Metadata API works in server components:
export const metadata = { title, description }, and for dynamic valuesexport async function generateMetadata({ params }). Values from layout and page are merged.next/headis a Pages Router API.15. At what URL is the file
public/logo.pngserved?Correct answer:
/logo.pngThe contents of
publicare 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/staticis the path for build-generated assets.16. How do you create a
GET /api/usersAPI endpoint in the App Router?Correct answer: A file
app/api/users/route.tsexporting aGETfunctionRoute Handlers use the Web
Request/ResponseAPIs:export async function GET(request: Request) { return Response.json(users) }.POST,PUT,PATCH,DELETEand others are supported. A folder can't contain bothroute.tsandpage.tsx.17. Which environment variables are available in browser code?
Correct answer: Only those prefixed with
NEXT_PUBLIC_, inlined at build timeNext.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. What does the
<Image>component fromnext/imagegive you?Correct answer: Size and format selection, lazy loading, no CLS
next/imagegeneratessrcset, serves modern formats (WebP/AVIF), lazy-loads by default and reserves space thanks towidth/height(orfill), preventing layout shifts. For the LCP image, usepreload(formerlypriority).19. Why does
<Image src="https://cdn.example.com/a.jpg" ... />produce a configuration error?Correct answer: External domains must be allowed in
images.remotePatternsinnext.configThe 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. What does
next/fontdo?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. Where do you import
useRouterfrom in the App Router?Correct answer:
next/navigationIn the App Router, navigation hooks -
useRouter,usePathname,useSearchParams,useParams- are imported fromnext/navigationand work in client components.next/routeris the Pages Router API. For a server-side redirect, useredirect().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. Readingwindowduring render breaks SSR and hydration. Thepathnameproperty onuseRouterexisted in the Pages Router; it isn't innext/navigation.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. 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/revalidateTagis 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. When does
getServerSidePropsrun in the Pages Router?Correct answer: On the server on every request
getServerSidePropsis SSR in the Pages Router: the function receives the request context (cookies, query) and returns props. At build time,getStaticPropsruns instead. In the App Router, both APIs are replaced by async server components.26. What does
getStaticPathsdo in the Pages Router?Correct answer: Returns the paths of a dynamic route to build
For a
pages/posts/[id].tsxpage withgetStaticProps, Next.js needs to know whichids to build ahead of time. Thefallbackoption defines behavior for other paths. The App Router counterpart isgenerateStaticParams.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
/aboutRoute 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. 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/routearen't public anyway, but_protects against accidentally creating a route and makes the structure clearer.29. Which route will catch
/docs/a/b/c?Correct answer:
app/docs/[...slug]/page.tsxA 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/docsitself. Next.js doesn't support asterisks in folder names.30. What do the
next buildandnext startcommands do?Correct answer:
buildcreates the production build,startruns itnext devis the development server with fast refresh.next buildcompiles the app, prerenders static routes and prints a report.next startruns the production server on the build output. For a static site there'soutput: 'export'.31. Which bundler does Next.js 16 use by default for
next devandnext build?Correct answer: Turbopack, without extra flags
Since Next.js 16, Turbopack is stable and used by default in both modes - the
--turbopackflag is no longer needed. You can go back to Webpack with the--webpackflag. If the project has a customwebpackconfig,next buildwithout the flag fails so that the config isn't silently ignored.32. In Next.js 16, what is the file formerly called
middleware.tsnamed?Correct answer:
proxy.tsThe
middlewareconvention is deprecated and renamed toproxyto emphasize its role at the network boundary (redirects, rewrites, headers). The exported function is also calledproxy. Proxy runs in the Node.js runtime; the edge runtime isn't supported there.33. How do you redirect the user to
/loginfrom a server component?Correct answer: Call
redirect('/login')fromnext/navigationredirect()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 intry/catch.useRouteris available only in client components, and<Navigate>is from React Router.34. How do you get the
?page=2query parameter in a server page?Correct answer: From the
searchParamsprop, which youawaitThe page receives
searchParamsas a promise. Reading the query makes the page dynamic, because the values are known only at request time. In client components, useuseSearchParams().paramscontains only the dynamic path segments.35. How do you load data in a server component?
Correct answer: Make the component
asyncand callawait fetch()or a DB queryServer 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. Where do you import global CSS in the App Router?
Correct answer: In the root
app/layout.tsxviaimportGlobal 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 noindex.htmlfile.37. Where does a
console.logfrom 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. What do you pass to
<Image>for an image that stretches over the whole parent block?Correct answer: The
fillprop, withposition: relativeon the parentWhen dimensions aren't known in advance, use
fill: the image is absolutely positioned and fills the parent, which must berelative,absoluteorfixed.sizeshints how wide the image will be so the browser doesn't download a file that's too large. Fitting is controlled withobject-fit.39. How do you lazy-load a heavy client component in Next.js?
Correct answer: With
next/dynamic(orReact.lazy+Suspense)const Chart = dynamic(() => import('./Chart'))moves the code into a separate chunk and lets you specifyloading. Thessr: falseoption disables server rendering but can be used only in client components. Server components don't end up in the bundle anyway.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:beforeInteractivefor critical scripts,afterInteractive(the default) andlazyOnloadfor secondary ones. A script loads once even when navigating between pages.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'innext.configA static export puts HTML, CSS and JS into the
outfolder, 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. What happens if
app/dashboard/contains bothpage.tsxandroute.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. How does
template.tsxdiffer fromlayout.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. Can you use the
useStateanduseEffecthooks 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. 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
prefetchprop (false,true,'auto'). In Next.js 16 prefetching became incremental: shared layouts are downloaded once.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.tsxorkey.47. How do you type the props of
app/blog/[slug]/page.tsxin Next.js 16?Correct answer: With the global helper
PageProps<'/blog/[slug]'>Next.js generates route types (during
next dev,next buildornext typegen), and thePageProps,LayoutPropsandRouteContexthelpers know theparamsshape for each path.NextPageis a Pages Router type.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. Can you use CSS Modules in Next.js without extra configuration?
Correct answer: Yes:
*.module.cssfiles are supported out of the boximport styles from './Button.module.css'andclassName={styles.primary}- class names become locally scoped. Sass (after installing thesasspackage), Tailwind and global CSS are supported too.50. What title does the page get with
export const metadata = { title: 'Profile' }in the page andtitle: { template: '%s | Shop', default: 'Shop' }in the layout?Correct answer:
Profile | Shoptitle.templatefrom the layout is applied to titles of child segments:%sis replaced with the page'stitle.defaultis used if a child segment doesn't set a title. This saves you from repeating the site name on every page.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
useParamshook fromnext/navigationPages and layouts get
paramsas a prop (a Promise in Next.js 16), while deeply nested client components can calluseParams()instead of receiving params through props.52. How do you generate
sitemap.xmlin 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.tsthat returns the list of URLssitemapis a special metadata file. Next.js serves it at/sitemap.xml; the function can fetch URLs from a database or CMS.53. Which file controls the
/robots.txtresponse?Correct answer:
app/robots.tsor a staticapp/robots.txtrobots.tsreturns an object of typeMetadataRoute.Robotswithrulesand an optionalsitemapURL, so you can vary rules per environment.54. How do you set the site favicon in the App Router?
Correct answer: Place
favicon.icoin theapp/folderIcon files are metadata file conventions.
iconandapple-iconcan also be generated in code withicon.tsx.55. How does
permanentRedirect()differ fromredirect()?Correct answer:
permanentRedirectreturns 308,redirectreturns 307Use 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. How do you redirect the old
/blog/:slugURLs to/news/:slugfor every request, without code in pages?// next.config.ts async redirects() { return [{ source: '/blog/:slug', destination: '/news/:slug', permanent: true }] }Correct answer: With
redirects()innext.config.tsConfig redirects run before the filesystem routes are matched. For many dynamic redirects (e.g. from a database), use
proxy.tsinstead.57. What happened to the
next lintcommand in Next.js 16?Correct answer: It was removed - run ESLint or Biome directly
next buildalso no longer runs the linter.eslint-config-nextuses the flat config format.58. Can the
app/folder live insidesrc/?Correct answer: Yes -
src/appworks; config files stay at the rootThe
srcfolder separates application code from config files. Ifapp/exists at the root too, the root one wins andsrc/appis ignored.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. UseuseRouteronly when there is no clickable link to render.60. What does the
replaceprop 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. 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. What is the
useLinkStatushook 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>. Preferloading.tsxand prefetching for instant navigations; the hook is a patch for slow transitions.63. How do you handle
POST /api/postsin 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
POSTfromroute.tsEach HTTP method is a named export:
GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS. Unsupported methods get a 405 response.64. Is the
altprop required onnext/image?Correct answer: Yes - use
alt=""for decorative imagesaltis a required prop of<Image>. An empty string tells assistive technology to skip a decorative image.65. Which
.envfile is meant for local secrets and should not be committed?Correct answer:
.env.local.env.localoverrides the defaults from.envand is normally in.gitignore..envand.env.productionhold non-secret defaults that can be committed.66. Why does
export const metadatain 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. Which pages does
app/dashboard/layout.tsxwrap?Correct answer: All pages under
/dashboard, nested ones tooLayouts nest: the root layout wraps the dashboard layout, which wraps every page below it. Nested segments can add their own layouts.
68. Where do you set
themeColorin Next.js 16?export const viewport = { themeColor: '#0f172a' }Correct answer: In the
viewportexport, not inmetadataViewport-related fields (
themeColor,colorScheme,width) moved out ofmetadatainto a separateviewportexport.69. How do you add a web app manifest for a PWA?
Correct answer: Add
app/manifest.tsor a staticmanifest.jsonmanifest.tsreturnsMetadataRoute.Manifestwith the name, icons and colors, and Next.js adds the<link rel="manifest">tag.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. 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 pageEscaping
<prevents XSS through the injected JSON. Types fromschema-dtshelp keep the data valid.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()fromnext/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. What does
export const dynamicParams = falsedo on a page withgenerateStaticParams(without Cache Components)?Correct answer: Params outside
generateStaticParamsreturn a 404By default unknown params are rendered on demand and cached.
dynamicParamsis not available when Cache Components are enabled.74. How do you serve the whole app under
/docs(e.g.acme.com/docs)?Correct answer: Set
basePath: '/docs'innext.config.tsbasePathis applied automatically to<Link>androuter.push. It's set at build time and can't change without rebuilding.75. Which
next/scriptstrategy loads a script during browser idle time, e.g. a chat widget?Correct answer:
lazyOnloadafterInteractive(the default) loads right after hydration starts;beforeInteractiveis for critical scripts before any Next.js code. Low-priority widgets fitlazyOnload.