Advertisement

Information Technology

Next.js Interview Questions & Answers

Prepare for your Next.js interview with 200+ curated questions and answers, organised into 40 topics from beginner to advanced. Each topic also has tutorials and MCQ practice.

40topics 200questions last updated
Advertisement
  1. API routes let you build backend endpoints directly inside your Next.js project, so you can handle things like form submissions or database calls without setting up a separate serv…

  2. In the Pages Router, the request object passed to your handler function gives you access to query parameters through req.query and to the submitted data through req.body, letting y…

  3. You check the req.method value at the top of your handler function and run different logic depending on whether the request is a GET, POST, or DELETE, returning an appropriate resp…

  4. You check for a valid session or authentication token at the start of your handler, usually by reading a cookie or an authorization header, and return a 401 unauthorized response i…

  5. Common pitfalls include not validating incoming data which can lead to bad or malicious input, running slow database queries without caching, and not setting proper rate limits, wh…

Authentication & Authorization in Next.js

All 5 questions
  1. Authentication confirms who a user is, usually through a login form or a third party sign in provider, while authorization decides what that authenticated user is allowed to do or…

  2. You check the user's session at the top of a server component or in middleware, and redirect them to the login page immediately if no valid session is found, before any of the prot…

  3. Middleware runs before a request reaches a page, so you can check the user's session cookie there and redirect unauthenticated users away from any protected route defined in your m…

  4. You store a role field on the user's account, such as admin or member, and check that role wherever access needs to be restricted, either in a server component before rendering or…

  5. Store authentication tokens in secure, httpOnly cookies so they cannot be accessed by client side JavaScript, always use HTTPS in production, set a reasonable expiration time, and…

Bundle Analysis & Code Splitting

All 5 questions
  1. Code splitting breaks your JavaScript into smaller chunks that load only when they are needed, instead of sending the entire application code to the browser on the first page load.…

  2. The next/dynamic function lets you import a component only when it is actually needed, such as when a modal opens, keeping that component's code out of the main bundle until the mo…

  3. You can use the official @next/bundle-analyzer package, which generates a visual report showing exactly which packages and files take up the most space in your JavaScript bundles,…

  4. You can remove unused dependencies, replace large libraries with smaller focused alternatives, use tree shaking friendly imports that only pull in the specific functions you need,…

  5. Layouts that wrap multiple routes are loaded once and reused across navigations within that layout, while each individual page's specific code is fetched separately when the user n…

  1. Caching means storing the result of a data fetch or a rendered page so that future requests can reuse that saved result instead of doing the same work again. This makes your applic…

  2. Next.js caches at several layers, including the fetch request cache which stores data fetching results, the full route cache which stores rendered pages, the router cache on the cl…

  3. You pass a revalidate option to the fetch call, specifying the number of seconds after which Next.js should fetch fresh data again instead of using the cached version, giving you f…

  4. You call the revalidatePath or revalidateTag function inside a server action or route handler after the update completes, telling Next.js to throw away the old cached version of a…

  5. A common pitfall is accidentally caching data that is different for each user, such as personalized dashboards or shopping carts, which can leak one user's data to another. You avo…

Client Components & Hydration

All 5 questions
  1. A client component is a piece of your app that runs in the browser and can use things like state, click handlers, and browser only APIs. You mark a file as a client component by ad…

  2. Hydration is the process where React takes the static HTML that was already sent from the server and attaches interactivity to it in the browser, such as making buttons clickable a…

  3. A hydration mismatch happens when the HTML rendered by the server does not match what the client renders during hydration, often caused by using values like the current date, rando…

  4. Server components can render client components as children, passing them data as props, while client components cannot directly import and render server components. This lets you k…

  5. You keep client components as small and focused as possible, pushing interactivity down to the smallest piece of the tree that actually needs it, rather than marking an entire page…

Cookies & Session Management in Next.js

All 5 questions
  1. The App Router gives you a cookies function from next/headers that you can call inside a server component to read any cookie sent with the request, letting you access things like a…

  2. You typically set cookies from a server action or a route handler using the cookies function, calling its set method with the cookie name, value, and options like httpOnly and secu…

  3. You generate a unique session identifier when a user logs in, store that identifier along with the user's data in a database or cache, save the identifier itself in a secure cookie…

  4. A signed cookie stores the session data directly inside the cookie itself, verified with a signature so it cannot be tampered with, while a server side session store keeps only a r…

  5. Always set the httpOnly flag so client side scripts cannot read the cookie, set the secure flag so it is only sent over HTTPS, choose an appropriate sameSite setting to prevent cro…

Custom App & Document in Pages Router

All 5 questions
  1. The custom App component, defined in pages/_app.js, wraps every page in your application, making it the perfect place to add global styles, shared layouts, or context providers tha…

  2. The custom Document component, defined in pages/_document.js, controls the initial HTML structure of your page, such as the html and body tags, and is the right place to add things…

  3. The custom Document component only renders on the server to generate the initial HTML shell, and it never re-renders on the client, so hooks that manage interactive client side sta…

  4. You typically add analytics initialization code inside the custom App component using a useEffect so it runs on route changes, while adding the actual third party script tag inside…

  5. In the App Router, the custom App and Document components are replaced by the root layout file, typically app/layout.js, which combines their responsibilities into a single file wh…

Data Fetching

All 5 questions
  1. You can simply use async and await directly inside a server component's function body, calling fetch or a database query, since server components run on the server and can handle a…

  2. Since client components cannot use async directly in their function body the way server components can, you typically fetch data inside a useEffect hook, storing the result in stat…

  3. You start all your fetch calls first without awaiting each one immediately, collect the resulting promises, and then use Promise.all to wait for all of them to finish together, so…

  4. You fetch the data inside a server component as usual, and then pass the resulting data as a normal prop to a client component that you render as its child, letting the client comp…

  5. Request deduplication automatically combines multiple identical fetch calls made during the same render into a single actual network request, so if several components on the same p…

Database Integration with Next.js

All 5 questions
  1. You typically install a database client or an ORM library like Prisma, set up a connection string in your environment variables, and then call database queries directly inside serv…

  2. Database credentials and connection strings must remain secret, and browsers cannot be trusted to keep secrets safe since anyone can view the JavaScript running on their machine. R…

  3. In serverless environments, creating a new database connection on every single request can quickly exhaust the database's connection limit, so you typically use a connection pooler…

  4. You perform the database update inside the server action itself, and after it completes, call revalidatePath or revalidateTag to refresh any cached pages that display that data, wh…

  5. Common issues include running the same query multiple times unnecessarily due to missing request deduplication, fetching more data than a page actually needs, and not adding proper…

  1. You can deploy a Next.js app to Vercel, the platform built by the creators of Next.js which offers zero configuration deployment, to other hosting providers that support Node.js se…

  2. You run the build command to generate an optimized production build, then use the start command to run a Node.js server that serves that build, making sure any required environment…

  3. You write a Dockerfile that installs dependencies, copies your source code, runs the build command, and then defines a start command to run the production server, allowing you to d…

  4. The standalone output mode generates a minimal, self contained folder with only the files your application actually needs to run, excluding unnecessary node modules, which results…

  5. Strategies include using rolling deployments that gradually shift traffic to the new version, blue green deployments where a completely separate environment is tested before switch…

Draft Mode & Preview Mode

All 5 questions
  1. Draft Mode lets content editors preview unpublished changes from a content management system before they go live, by temporarily bypassing the normal static caching so the page alw…

  2. You check whether Draft Mode is currently enabled inside your data fetching function, and if it is, you request the draft version of the content from your content management system…

  3. You require a secret token as a query parameter when enabling Draft Mode, checking that the provided token matches a secret value stored in your environment variables before actual…

  4. When Draft Mode is enabled, Next.js automatically switches that page to render dynamically on every request instead of using the static cached version, ensuring editors always see…

  5. You configure your CMS to generate a preview link containing a secret token and the content slug, pointing to your Draft Mode enabling route, which verifies the secret, enables Dra…

Dynamic Routes & Catch-All Segments

All 5 questions
  1. A dynamic route lets a single page template handle many different URLs by using a folder name wrapped in square brackets, such as [id], which captures that part of the URL as a par…

  2. A catch-all segment, written with three dots inside brackets like [...slug], matches any number of URL segments after a certain point, capturing them as an array, which is useful f…

  3. An optional catch-all segment, written with double brackets like [[...slug]], works just like a regular catch-all segment but also matches the base route with no additional segment…

  4. You export a generateStaticParams function from your dynamic route's page file that returns an array of parameter objects, and Next.js will use these to build a separate static pag…

  5. You use generateStaticParams to pre-build only the most important or most visited pages ahead of time, and let the remaining pages generate on demand the first time they are reques…

Edge Runtime vs Node.js Runtime

All 5 questions
  1. The Node.js Runtime is the full Node.js environment with access to all Node.js APIs and packages, while the Edge Runtime is a lighter, faster environment that runs closer to your u…

  2. The Edge Runtime runs on servers distributed across many geographic locations, so a request from a user in one country can be handled by a server physically close to them rather th…

  3. The Edge Runtime does not support certain Node.js specific APIs, cannot use many npm packages that rely on native Node.js modules, has a smaller memory and execution time limit, an…

  4. You export a runtime constant set to either edge or nodejs from your route handler or page file, telling Next.js which environment to run that specific piece of code in, allowing y…

  5. Consider whether the feature needs low latency for a globally distributed audience, whether it depends on Node.js specific packages or file system access, how much memory and execu…

Environment Variables & Configuration Management

All 5 questions
  1. You create a file named .env.local in the root of your project and define key value pairs there, which Next.js automatically loads and makes available to your server side code thro…

  2. A regular environment variable is only available on the server and stays hidden from the browser, while one prefixed with NEXT_PUBLIC gets included in the JavaScript bundle sent to…

  3. You create separate files such as .env.development, .env.production, and rely on your hosting platform's environment variable settings for staging or production secrets, since Next…

  4. You can write a small validation script or use a library like zod to define a schema for your expected environment variables, checking them once at startup and throwing a clear err…

  5. The biggest risk is accidentally exposing a secret to the browser by using the NEXT_PUBLIC prefix on something sensitive, or committing an env file containing real secrets to versi…

Error Handling & Not Found Pages

All 5 questions
  1. You add a file named error.js inside a route folder, which must be a client component, and Next.js automatically shows it whenever an error occurs while rendering that route or any…

  2. You add a file named not-found.js to your app folder, and Next.js automatically shows it whenever a route does not match any page, or whenever you manually call the notFound functi…

  3. You call the notFound function imported from next/navigation inside your page or data fetching logic whenever the requested data cannot be found, which immediately stops rendering…

  4. The global-error.js file, placed at the root of the app folder, catches errors that occur in the root layout itself, which regular error.js files cannot catch since they are nested…

  5. You place error.js files at strategic points in your route structure, such as near features that are more likely to fail, use a shared error reporting service to log errors to a mo…

Form Handling & Validation in Next.js

All 5 questions
  1. You pass your server action function directly to the form element's action attribute, and Next.js automatically handles collecting the form data and sending it to your server actio…

  2. Inside your server action, you check the submitted values against your validation rules, often using a library like zod, and if validation fails, you return an object describing th…

  3. You use the useFormStatus hook inside a child component of the form, which tells you whether the form is currently submitting, letting you disable the submit button or show a loadi…

  4. You read the uploaded file directly from the FormData object inside your server action using its field name, which gives you a File object that you can then process, save to disk,…

  5. Optimistic UI means immediately updating the interface as if the action already succeeded, before the server actually confirms it, using the useOptimistic hook to show the expected…

Image & Font Optimization

All 5 questions
  1. The Image component automatically resizes images to fit the size they are displayed at, serves modern efficient formats like WebP when supported, lazy loads images that are not yet…

  2. The next/font module lets you import fonts, including Google Fonts, directly into your project, automatically hosting the font files alongside your application and eliminating extr…

  3. You use the sizes prop along with fill or a responsive width and height, telling the browser roughly how large the image will be displayed at different screen widths, allowing Next…

  4. You add the external domain's hostname to the images configuration inside your next.config.js file, since Next.js only optimizes images from domains you explicitly trust, preventin…

  5. You can mark the most important above the fold image with the priority prop so it loads immediately without lazy loading, use a blur placeholder to show a low quality preview while…

Internationalization (i18n) in Next.js

All 5 questions
  1. Internationalization means preparing your application to support multiple languages and regions, such as translating text and formatting dates or currency differently depending on…

  2. You add a dynamic locale segment as the first part of every route, such as app/[locale]/page.js, and read the locale parameter to determine which language's content and translation…

  3. Middleware can inspect the accept-language header sent by the browser, compare it against the languages your application supports, and redirect the visitor to the matching locale p…

  4. You generate alternate language links in your metadata for each translated version of a page, telling search engines which other language versions exist and how they relate to each…

  5. Store translations in structured files organized by language and feature, use a dedicated translation management library or service to keep them synchronized, avoid hardcoding text…

Layouts & Templates

All 5 questions
  1. A layout is a component defined in a layout.js file that wraps a page and any of its nested pages, letting you share common user interface elements like a navigation bar or sidebar…

  2. A layout preserves its state and does not re-render when navigating between pages that share it, while a template, defined in a template.js file, creates a fresh instance and re-re…

  3. Each folder in your route structure can have its own layout.js file, and Next.js automatically nests them, wrapping the innermost page with its closest layout first, and then wrapp…

  4. You use a route group, created by wrapping a folder name in parentheses, such as (marketing), which lets you organize routes and apply a shared layout to them without that folder n…

  5. You fetch shared data, such as the current user's profile, directly inside the layout component itself since layouts can also be async server components, and pass that data down to…

Loading UI & Streaming with Suspense

All 5 questions
  1. You add a file named loading.js inside the same route folder as your page, and Next.js automatically displays it while the page's server component is fetching data, giving users in…

  2. Streaming lets Next.js send parts of a page to the browser as soon as they are ready, instead of waiting for every piece of data on the page to finish loading first. This means fas…

  3. You wrap each slow loading section of your page in its own Suspense component with a specific fallback, letting each section stream in independently as soon as its own data is read…

  4. Search engine crawlers typically wait for the full page to finish rendering before indexing it, so streaming does not usually harm SEO for content that is important for search rank…

  5. You design skeleton loading placeholders that closely match the actual size and shape of the content that will eventually appear, use consistent Suspense boundaries so sections loa…

Metadata API & SEO Optimization

All 5 questions
  1. You export a metadata object from your page or layout file, defining fields like title and description, and Next.js automatically generates the correct HTML head tags for search en…

  2. You export an async function called generateMetadata from your page file, fetch the relevant data inside it just like you would in the page component, and return a metadata object…

  3. You include openGraph and twitter fields inside your metadata object, specifying an image, title, and description that social media platforms use to build an attractive preview car…

  4. You create special files named sitemap.js and robots.js in your app folder, exporting functions that return the list of URLs to include in your sitemap and the crawling rules for s…

  5. You embed a script tag containing JSON-LD structured data describing your content, such as marking up a recipe with its ingredients and cooking time, or an article with its author…

  1. Middleware is a special function defined in a middleware.js file at the root of your project that runs before a request completes, letting you inspect, modify, redirect, or block r…

  2. You export a config object with a matcher array from your middleware file, specifying the exact paths or patterns where the middleware should run, preventing it from executing unne…

  3. You read information available on the request object, such as geolocation data or the user agent header, inside your middleware function, and then return a redirect response pointi…

  4. You return a rewrite response from your middleware function pointing to the internal path you actually want to serve, and Next.js will render that different page while keeping the…

  5. Since middleware runs on the Edge Runtime and executes before every matched request, you should keep its logic fast and lightweight, avoid making slow external API calls or databas…

Next.js Project Setup & Configuration

All 5 questions
  1. You run the create-next-app command in your terminal, which walks you through a few setup questions like whether you want TypeScript or Tailwind CSS, and then generates a fully wor…

  2. The next.config.js file lets you customize how your Next.js application builds and runs, controlling things like allowed image domains, custom redirects, environment variable expos…

  3. The App Router uses an app folder where each folder represents a route segment and special files like page.js, layout.js, and loading.js define behavior, while the Pages Router use…

  4. You add a paths configuration inside your tsconfig.json or jsconfig.json file, mapping a short alias like @/components to your actual folder path, letting you write shorter, cleane…

  5. You configure path aliases in your tsconfig.json for absolute imports, extend the webpack configuration function inside next.config.js for any custom build behavior you need, and o…

On-Demand Revalidation Strategies

All 5 questions
  1. Time based revalidation refreshes cached content automatically after a set number of seconds, while on-demand revalidation lets you manually trigger a cache refresh at the exact mo…

  2. You call revalidatePath with the exact path of the page you want to refresh, typically inside a server action or route handler right after a database update completes, and Next.js…

  3. You tag your fetch requests with a specific tag name using the next options, and later call revalidateTag with that same tag name to invalidate every cached fetch result sharing th…

  4. You create a route handler that receives a webhook notification from your CMS whenever content is published or updated, verify the request is legitimate using a shared secret, and…

  5. revalidatePath is simple and direct but requires you to know every specific path affected by a change, which can be error prone in complex apps, while revalidateTag is more flexibl…

Pages Router Data Fetching (getStaticProps, getServerSideProps & getStaticPaths)

All 5 questions
  1. getStaticProps is a special function you export from a page file that runs at build time, fetching data and passing it to your page component as props, allowing Next.js to generate…

  2. getServerSideProps runs on every single request rather than at build time, fetching fresh data each time a user visits the page, which is useful for content that changes frequently…

  3. getStaticPaths tells Next.js which dynamic route parameter values should be pre-built into static pages at build time, returning a list of paths, while getStaticProps then runs sep…

  4. Setting fallback to false means any path not listed results in a 404 page, setting it to true shows a fallback loading state while generating the page on the first request and cach…

  5. In the App Router, you simply use an async server component and call fetch or a database query directly inside it, using the next.revalidate option on your fetch call to replicate…

Parallel Routes & Intercepting Routes

All 5 questions
  1. Parallel routes let you render two or more independent pages within the same layout at the same time, using named slots defined with an at sign prefix, which is useful for building…

  2. You create a folder starting with an at sign, such as @analytics, inside the same directory as your layout, and Next.js automatically passes its rendered content into the layout as…

  3. An intercepting route lets you show a different view when a link is clicked from within your app, such as opening a photo in a modal overlay, while still showing the full dedicated…

  4. You create a parallel route slot for the modal content, and inside that slot, use an intercepting route to catch navigation to a specific path, rendering the modal on top of the cu…

  5. Parallel routes shine when different sections of a page need independent loading and error states, independent data fetching, or need to support features like modals that intercept…

Redirects & Rewrites Configuration

All 5 questions
  1. You add a redirects function inside your next.config.js file, returning an array of redirect rules that each specify a source path, a destination path, and whether it should be a p…

  2. A rewrite serves content from a different internal path while keeping the original URL visible in the browser's address bar, unlike a redirect which actually changes the URL the vi…

  3. You use a named parameter with a colon inside your source path, such as :slug, and reference that same parameter name inside your destination path, letting a single rule handle man…

  4. Since the redirects function in next.config.js only supports static, build time rules, you use middleware instead for conditional redirects that depend on runtime information like…

  5. Keep your redirect rules organized in a clearly documented list, regularly audit and remove ones that are no longer needed, avoid chaining multiple redirects together since each ho…

Rendering (SSR/SSG/ISR)

All 5 questions
  1. Server side rendering, called SSR, generates the page fresh on every request. Static site generation, called SSG, generates the page once at build time and reuses it for every visi…

  2. Static site generation produces the fastest possible loading pages since the HTML is already fully built and can be served instantly from a content delivery network, making it idea…

  3. Server side rendering is the right choice when a page's content must be completely up to date on every single visit and cannot tolerate any staleness, such as a live stock ticker,…

  4. Incremental static regeneration serves the existing fast, cached static page to visitors while a new version is being generated in the background after the revalidation period pass…

  5. You would use static site generation for the marketing pages since they rarely change, incremental static regeneration for product pages that update periodically but benefit from f…

Route Handlers (API Route.js)

All 5 questions
  1. A route handler is a file named route.js placed inside a folder within your app directory, exporting functions named after HTTP methods like GET or POST, letting you build backend…

  2. You access query parameters through the request URL's searchParams property, and read the request body by calling a method like json on the request object, which returns a promise…

  3. The second argument passed to your route handler function contains a params object, which you await to access the dynamic segment values captured from the URL, letting you build en…

  4. You track the number of requests coming from a specific identifier, such as an IP address or an API key, over a time window, usually using an external store like Redis for reliabil…

  5. You construct your response using the Response constructor, passing a headers object that includes the necessary CORS headers like Access-Control-Allow-Origin, allowing browsers on…

Routing (App/Pages Router)

All 5 questions
  1. In the App Router, every folder inside the app directory represents a segment of the URL path, and adding a file named page.js inside that folder makes it a visitable route, so the…

  2. In the Pages Router, each file directly inside the pages folder becomes a route based on its file name, such as pages/about.js becoming the about page, while the App Router instead…

  3. In the App Router, you import the useRouter hook from next/navigation inside a client component, and call its push method with the desired path, which navigates the user to that ne…

  4. You import the Link component from next/link and use it in place of a regular anchor tag for internal navigation, which automatically preloads the linked page's code in the backgro…

  5. You wrap folder names in parentheses, such as (marketing) or (dashboard), to create route groups that let you apply different layouts or organize files for related sections of your…

Security Best Practices in Next.js

All 5 questions
  1. Anything included in a client component becomes part of the JavaScript bundle sent to every visitor's browser, meaning anyone can view it by inspecting the page, so secrets like AP…

  2. React automatically escapes content rendered inside JSX, which prevents most cross site scripting attacks by default, but you should still avoid using dangerouslySetInnerHTML with…

  3. You add a headers function inside your next.config.js file, defining custom response headers like Content-Security-Policy or X-Frame-Options that apply across your application, hel…

  4. You always validate and sanitize the incoming data inside the server action itself using a schema validation library, never trust that data matches what your form actually intended…

  5. Regularly update Next.js and your project's dependencies to receive security patches, use automated tools that scan for known vulnerabilities in your dependencies, remove packages…

Server Actions & Mutations

All 5 questions
  1. A server action is a function marked with a use server directive that runs only on the server but can be called directly from a client component or a form, letting you update data,…

  2. You import the server action function into your client component and call it directly inside an event handler, such as onClick, just like you would call any other asynchronous func…

  3. After a server action completes its update, you typically call revalidatePath or revalidateTag inside it to clear the relevant cached data, which causes Next.js to refetch and re-r…

  4. You wrap the risky part of your server action in a try and catch block, and instead of letting an unhandled error crash the request, you return a structured object describing what…

  5. Since server actions are exposed as callable endpoints, you must treat every input they receive as untrusted, just as you would with a public API, always validating the data's shap…

Server Components

All 5 questions
  1. A server component renders entirely on the server and sends only the resulting HTML and minimal necessary data to the browser, without shipping its own JavaScript to the client, wh…

  2. Server components render once on the server to produce static HTML and do not run again in the browser afterward, so hooks that manage ongoing client side state or respond to brows…

  3. Server components reduce the amount of JavaScript sent to the browser since their code never needs to run client side, they can access backend resources like databases directly wit…

  4. You default to server components for anything that does not need interactivity, browser only APIs, or React state, and only reach for client components for the specific, usually sm…

  5. You can pass any value that can be serialized, such as strings, numbers, plain objects, and arrays, but you cannot pass things like functions, class instances, or database connecti…

State Management in Next.js Apps

All 5 questions
  1. Local component state, managed with the useState hook inside a client component, is enough when a piece of data only matters to that one component and its direct children, such as…

  2. You use React Context to create a shared piece of state accessible from any component wrapped inside its provider, avoiding the need to pass that data down manually through many la…

  3. You typically reach for a dedicated library when your application's shared state becomes complex, needs to be updated frequently from many different places, or requires more advanc…

  4. In Next.js, much of what would traditionally be client side state, like data fetched from an API, can instead live on the server and be refetched through navigation or revalidation…

  5. You use the useOptimistic hook to immediately show the expected new state, such as an increased like count, right when the user clicks, while the actual server action runs in the b…

Styling in Next.js (CSS Modules, Tailwind & Styled Components)

All 5 questions
  1. CSS Modules let you write regular CSS in a file named with a .module.css extension, and Next.js automatically scopes those class names so they only apply to the component that impo…

  2. You can choose to include Tailwind CSS when creating your project with create-next-app, or install and configure it manually afterward, and once set up, you apply pre-built utility…

  3. Many CSS in JS libraries require a use client directive since they rely on runtime JavaScript to inject styles, and some libraries provide specific integration instructions for the…

  4. You typically place truly global styles, like base typography and CSS variable definitions, in a single global stylesheet imported once in your root layout, while keeping component…

  5. Consider your team's familiarity with each approach, whether you prefer writing traditional CSS or utility classes, how much you value zero runtime overhead which favors CSS Module…

Testing Next.js Applications

All 5 questions
  1. Unit tests check individual functions or small components in isolation, integration tests check how several pieces work together such as a form and its validation logic, and end to…

  2. You typically use a testing library like Jest along with React Testing Library, rendering the component in a test environment and then making assertions about what should appear on…

  3. Since server components are async functions, you can call them directly in a test environment, await their result, and then check the returned output, though many teams also rely m…

  4. You use a tool like Playwright or Cypress, which controls an actual browser, to write a test script that visits your application, clicks buttons, fills out forms, and asserts that…

  5. You would write many fast unit tests for individual functions and small components since they run quickly and catch issues early, a moderate number of integration tests for importa…

Third-Party Script Optimization

All 5 questions
  1. The next/script component gives you fine grained control over when and how third party scripts load, letting you choose strategies that avoid blocking the main page content from re…

  2. beforeInteractive loads a script before any page content becomes interactive, useful for critical scripts needed immediately, afterInteractive loads it soon after the page becomes…

  3. You pass an onLoad callback function to the Script component, which Next.js automatically calls once the script has fully finished loading, letting you safely run any code that dep…

  4. You would use browser performance tools to measure how much each script delays interactivity and blocks the main thread, prioritize which scripts truly need to load early versus wh…

  5. Only load scripts from sources you trust, since a compromised third party script can inject malicious code directly into your page, consider using the integrity attribute to verify…

Turbopack & Build Performance

All 5 questions
  1. Turbopack is a fast bundler built specifically for JavaScript and TypeScript applications, designed to replace the older bundling tools used by Next.js, offering significantly fast…

  2. Turbopack uses an incremental computation approach, caching the results of previous work at a very fine grained level, so when you change a single file, it only reprocesses that fi…

  3. You can continue using the standard Webpack based build for production while still benefiting from Turbopack's speed during local development, or check the plugin's compatibility s…

  4. You would time your typical development workflows, such as cold server startup and the delay after saving a file until changes appear in the browser, running the same measurements…

  5. You can reduce the amount of code that needs to be processed by removing unused dependencies, split very large pages into smaller more focused components, use incremental static re…

TypeScript with Next.js

All 5 questions
  1. You can choose TypeScript when running create-next-app, or add it to an existing JavaScript project by installing TypeScript and its type definitions and renaming your files to use…

  2. You define a type or interface describing the shape of the params object your page expects, matching the dynamic segments in your folder structure, and use it to type the props par…

  3. You define an interface describing the expected shape of the API response, and use it as the return type for your data fetching function, letting TypeScript check that your JSX cor…

  4. You define types for both the expected form data shape and the return value of your server action, often combining this with a runtime validation library like zod to ensure the dat…

  5. You enable strict mode in your tsconfig.json file, which turns on a comprehensive set of stricter type checking rules, such as requiring explicit handling of potentially null or un…

Web Vitals & Performance Monitoring

All 5 questions
  1. Core Web Vitals are a set of specific metrics that measure real user experience, including how quickly the main content loads, how quickly the page responds to the first user inter…

  2. You call the useReportWebVitals hook inside a client component, providing a callback function that receives each performance metric as it becomes available, letting you send that d…

  3. You can optimize the loading of your largest visible element, often a hero image or heading, by using the priority prop on important images, preloading critical fonts with next/fon…

  4. You reserve the correct amount of space for elements before their final content loads, such as setting explicit width and height on images and ad containers, using next/font to avo…

  5. You combine automated performance testing tools that run on every pull request to catch regressions early, real user monitoring that continuously reports actual Core Web Vitals dat…