Next Js Interview Questions
Explore the most important Next.js interview questions including SSR, SSG, ISR, routing, performance optimization, and real-world implementation examples.
Interview Questions for Freshers
1. What is Next.js?
Next.js is a framework built on top of React that adds some extra functionalities such as server-side rendering (SSR), static site generation (SSG), file-based routing, API routes, and more.
React is just a UI library used for building components, while Next.js is a full-fledged framework that takes care of routing, rendering, backend functionality, and more.
2. How does Next.js work?
Next.js works as a React framework that handles rendering, routing, and optimization automatically, making web apps faster and SEO-friendly.
Pre-rendering: Pages can be rendered on the server (SSR) or per-rendered at build time (SSG) for faster load and better SEO.
Routing: File-based routing automatically maps pages to URLs.
API Routes: Allows backend functionality within the application. Each file inside pages/api/ automatically becomes an API endpoint.
Automatic Code Splitting: Loads only the necessary JavaScript for each page, improving performance.
Optimized Builds: Bundling, minification, and image optimization happen out-of-the-box.
Easy Deployment: Supports multiple deployment options like static site hosting and serverless functions, simplifying the release process.
This enables developers to build full-stack, production-ready applications with minimal configuration.
3. What are the different rendering methods in Next.js?
Next.js offers various rendering options to improve performance and SEO. The different rendering options in Next.js are Server-Side Rendering (SSR), Static Site Generation (SSG), Incremental Static Regeneration (ISR), and Client-Side Rendering (CSR). These options decide where the HTML will be created – at build time, at request time, or on the client side.
Server-Side Rendering (SSR)
The page is rendered on the server for every request.
Good for dynamic, frequently changing data.
Better SEO.
Example
1function App() {
2 const user = "John";
3 return <Parent user={user} />;
4}
5
6function Parent({ user }) {
7 return <Child user={user} />;
8}
9
10function Child({ user }) {
11 return <GrandChild user={user} />;
12}
13
14function GrandChild({ user }) {
15 return <h1>{user}</h1>;
16}
17
18export async function getServerSideProps() {
19 return { props: { data: "SSR Data" } };
20}Static Site Generation (SSG)
Page is generated at build time.
Very fast performance.
Good for static content.
Example
1export async function getStaticProps() {
2 return { props: { data: "Static Data" } };
3}Incremental Static Regeneration (ISR)
Static pages updated after deployment.
Revalidates data at a specified interval.
Example
1export async function getStaticProps() {
2 return {
3 props: { data: "ISR Data" },
4 revalidate: 10
5 };
6}Client-Side Rendering (CSR)
Data fetched in the browser.
Used for highly interactive content.
Example
1function App() {
2 const [data, setData] = useState(null);
3
4 useEffect(() => {
5 fetch('/api/data')
6 .then(res => res.json())
7 .then(data => setData(data));
8 }, []);
9
10 if (!data) return <p>Loading...</p>;
11 return <h1>{data}</h1>;
12}4. What is Incremental Static Regeneration (ISR) in Next.js?
Incremental Static Regeneration (ISR) is a feature of Next.js that enables dynamic updates to static pages after deployment without requiring the entire app to be rebuilt. ISR is a combination of Static Site Generation (SSG) and dynamic updates. Next.js uses the revalidate property to regenerate the page in the background after a specified time interval when a request is received.
Example
1export async function getStaticProps() {
2 const data = await fetch("https://api.example.com/posts")
3 .then(res => res.json());
4
5 return {
6 props: { data },
7 revalidate: 10, // Regenerate page every 10 seconds
8 };
9}
10
11export default function Page({ data }) {
12 return <div>{data.title}</div>;
13}5. How does Next.js handle routing?
For routing, Next.js uses a file-based routing system. This means that instead of having to define routes manually, as is the case with React Router, routes are automatically set up based on the folder and file structure in the pages or app directory. This means that each file is a route, and subfolders are sub-routes.
6. How does Next.js handle client-side navigation?
For handling client-side routing in Next.js, the next/link component and the useRouter hook are used. When using Next.js for navigation, the entire page is not reloaded, as it happens in traditional routing. Instead, Next.js relies on client-side routing for updating the URL and loading the new page without performing a full page reload, which is beneficial for performance and offers a better user experience, just like SPAs.
Link Component
1import Link from 'next/link';
2
3const MyComponent = () => (
4 <Link href="/another-page">
5 <a>Go to another page</a>
6 </Link>
7);Programmatic Navigation with useRouter
1import { useRouter } from 'next/router';
2
3const MyComponent = () => {
4 const router = useRouter();
5
6 const handleClick = () => {
7 router.push('/another-page');
8 };
9
10 return <button onClick={handleClick}>Go to another page</button>;
11};7. What is the purpose of the public folder in a Next.js project?
The public folder in Next.js is used for storing static assets such as images, fonts, icons, and other files that need to be accessible from the root URL. Files stored in the public folder are served directly from the root URL without any further configuration. They are not processed by Webpack and can be accessed through a simple path.
Example
If you have an image called logo.png in the public folder, you can access it in your code using the path /logo.png. For example, <img src="/logo.png" alt="Logo" /> will display the logo image on your page.
8. What are API routes in Next.js and how do you create them?
API Routes in Next.js enable you to build backend API routes within a Next.js application. They help you deal with server-side tasks such as database operations, authentication, form handling, and API calls from other services without requiring a separate backend server running Express.js.
API routes are server-side-only and do not get bundled in the client-side code. They are often used to build full-stack applications within a single Next.js project.
How API Routes Works
Any file inside pages/api/ automatically becomes an API endpoint.
The file exports a default function that receives: req (request object) and res (response object)
The route is accessible at /api/<filename>.
Example
1export default function handler(req, res) {
2 if (req.method === 'GET') {
3 res.status(200).json({ message: 'Hello from API Route!' });
4 } else {
5 res.status(405).json({ message: 'Method Not Allowed' });
6 }
7}9. What is styled-jsx in Next.js ?
styled-jsx is a built-in CSS-in-JS solution in Next.js that allows you to write component-level styles that are automatically scoped and encapsulated. Key points :
Styles applied to a component do not affect other components.
Allows seamless addition, modification, or removal of styles without impacting unrelated parts of the application.
Ensures predictable and maintainable styling for Next.js components.
10. What are the common methods of data fetching in Next.js ?
In Next.js, you have a number of built-in data fetching APIs such as getStaticProps, getServerSideProps and getStaticPaths. getStaticProps is used for data fetching at build time for static site generation. getServerSideProps is used for data fetching on every request, which is ideal for dynamic pages that require the latest data.getStaticPaths is used for dynamic routes to determine which paths should be pre-rendered at build time. Apart from these, you also have client-side data fetching APIs such as useEffect and API Routes if you require more flexibility or want to fetch data after the initial page load.
11. What is the purpose of the getStaticPaths function in Next.js ?
getStaticPaths is a function that can be used in Next.js with Static Site Generation (SSG) for dynamic routes. This function informs Next.js which dynamic routes should be pre-rendered at build time. This is necessary when using getStaticProps with dynamic routes, so Next.js knows which pages to pre-render ahead of time.
Example
1export async function getStaticPaths() {
2 return {
3 paths: [
4 { params: { id: "1" } },
5 { params: { id: "2" } }
6 ],
7 fallback: false
8 };
9}
10
11export async function getStaticProps({ params }) {
12 return {
13 props: {
14 id: params.id
15 }
16 };
17}
18
19export default function BlogPost({ id }) {
20 return <h1>Blog ID: {id}</h1>;
21}12. What is the purpose of the _app.js file in Next.js ?
The `app.js` file in Next.js enables you to override the default `App` component and manage the top-level structure of your app. It is a wrapper for all the page components, which allows you to add global styles, shared layouts, providers (such as Context or Redux), and application-level logic. This ensures a consistent layout and behavior for all pages.
Why use _app.js?
Apply global CSS
Wrap pages with layout components
Add global state providers
Initialize third-party libraries
Persist layout across page navigation
13. Why use Create Next App to set up a Next.js project ?
Create Next App is the official CLI tool offered by the Next.js team to quickly start a new Next.js app with the best practices set up. It automatically configures the project structure, dependencies, support for TypeScript (optional), ESLint, and other necessary configurations to get started with development.
Key features of Create Next App :
Interactive Setup: Executing `npx create-next-app@latest` (with no arguments) initiates an interactive experience that guides you through the project setup process.
Dependency-Free: Project initialization is remarkably fast, taking just a second, as Create Next App comes with zero dependencies.
Offline Capabilities: Create Next App can automatically detect offline status and bootstrap your project using the local package cache.
Example Support: It can initialize your application with an example from the Next.js examples collection (e.g., `npx create-next-app --example api-routes`).
Thorough Testing: As part of the Next.js monorepo, this package undergoes testing with the same integration test suite as Next.js itself. This ensures consistent and expected behavior with every release.
14. What is Fast Refresh in Next.js ?
Fast Refresh is a development tool in Next.js that allows for immediate changes in the browser when you make changes to React components, without losing component state. Fast Refresh is an optimized version of Hot Module Replacement (HMR) for React. Fast Refresh will only update the modules that have been changed and will always keep local state.
How Fast Refresh Works :
You edit a component file.
Next.js detects the change.
Only the updated module reloads.
Component state is preserved (if possible).
15. What is the purpose of useEffect in React and how does it relate to Next.js ?
The useEffect hook in React is used to handle side effects in functional components, such as data fetching, subscriptions, timers, or DOM manipulation. It is executed after the component has been rendered and can be managed by using a dependency array.
The useEffect hook in Next.js only runs on the client-side because it is executed after the component has been mounted in the browser. It does not run on server-side rendering (SSR). Hence, the useEffect hook is generally used for client-side code, such as accessing window or localStorage, or running browser-specific code.
Usage in Next.js:
Can be used for client-side data fetching using fetch or libraries like Axios or SWR.
Runs after the component renders, making it suitable for actions that should happen on the client side.
Complements Next.js data fetching methods like getServerSideProps and getStaticProps for client-side logic.
Interview Questions for Experienced
1. How to implement dynamic routing in Next.js?
Dynamic routing in Next.js allows you to create pages where the URL contains a dynamic part rather than a static one. Next.js has a file-based routing system, which means that the file system in the pages or app directory will automatically be used as your routes. To create dynamic routes, you need to enclose the file or folder name in square brackets, for example, [id].
This is usually used for pages such as blog posts, product detail pages, user profile pages, or any type of content that has a URL based on a unique identifier. Next.js will automatically extract the dynamic part of the URL and pass it to you inside your component.
Dynamic routes can be created using different rendering techniques, such as Static Site Generation (SSG), Server-Side Rendering (SSR), or Incremental Static Regeneration (ISR), depending on the data fetching and updating needs.
2. How to pass data between pages in Next.js ?
In Next.js, data can be shared between pages via URL parameters (query strings or dynamic routes), global state management (Context API or third-party state management solutions), browser storage (localStorage/sessionStorage), or by re-fetching the data on the destination page using SSR or SSG. The choice of method depends on the nature of the data.
Example using Query Parameters
1import Link from "next/link";
2
3<Link href={{ pathname: "/profile", query: { id: 1 } }}>
4 Go to Profile
5</Link>
6
7// Access it on the next page:
8import { useRouter } from "next/router";
9
10const router = useRouter();
11console.log(router.query.id);Example using Dynamic Routes
1//Navigate like:
2<Link href="/blog/123">Blog Post</Link>
3//Access param:
4const { id } = router.query;3. What are dynamic imports in Next.js ?
Dynamic imports in Next.js enable you to import components or modules only when they are required, rather than bundling them in the initial JavaScript bundle. This enhances the performance of the application by reducing the size of the initial bundle. The next/dynamic function in Next.js is used to implement dynamic imports.
Example
1import dynamic from "next/dynamic";
2
3const HeavyComponent = dynamic(() => import("../components/HeavyComonent"));
4
5export default function Page() {
6 return <HeavyComponent />;
7}4. What do you understand by code splitting in Next.js ?
Code splitting in Next.js is a performance optimization technique in which the JavaScript bundle of the application is automatically split into smaller chunks, and only the required code for a particular page is loaded when the page is accessed. Rather than loading the entire application at once, Next.js loads only what is required.
There are mainly three approaches to code splitting:
Entry Points: Employed for manual code splitting by configuring entry points.
Avoiding Redundancy: Utilizes entry dependencies or the SplitChunksPlugin to deduplicate and divide chunks.
Dynamic Imports: Achieves code splitting through inline function calls within modules.
5. How do you optimize images in Next.js ?
For image optimization in Next.js, there is a built-in component called next/image that automatically takes care of lazy loading, resizing, format optimization (such as WebP), and responsive images. This enhances performance by loading images of the correct size according to the device and viewport.
Example
1import Image from "next/image";
2
3export default function Page() {
4 return <Image src="/image.jpg" alt="My Image" width={200} height={200} />;
5}6. What is Next.js Middleware ?
Middleware is a feature in Next.js that enables you to execute code before a request is completed. This happens on the server (Edge Runtime) before the page or API route is rendered. Middleware is often used for authentication, redirection, logging, localization, and request modification. It assists in intercepting requests and determining how they should be handled.
How Middleware Works :
Runs before a request reaches a route
Can modify request or response
Can redirect or rewrite URLs
Executes at the Edge (fast and lightweight)
7. How do you handle errors and error pages in Next.js ?
In Next.js, error handling and error pages are managed by Next.js using built-in error handling features such as custom 404 and 500 error pages, error boundaries in the App Router, and try/catch blocks in data fetching functions such as getServerSideProps and getStaticProps. Next.js enables you to provide a custom error UI while preserving the correct HTTP status code.
Example
1//Custom 404 Page
2//Create: pages/404.js
3export default function Custom404() {
4 return <h1>404 - Page Not Found</h1>;
5}
6
7//Custom 500 Page
8//Create: pages/500.js
9export default function Custom500() {
10 return <h1>500 - Server Error</h1>;
11}8. How do you add meta tags and title tags in Next.js using the Head component ? Why is this important for SEO?
In Next.js, you can use the Head component from next/head to add meta tags, titles, and other head elements. This way, you can define your own SEO-related metadata such as title, description, keywords, Open Graph properties, and more for each page. Using proper meta tags will make it easier for search engines to understand the content of the page, and you can also control how your page will look when it is shared on social media sites.
Example
1import Head from "next/head";
2
3export default function Page() {
4 return (
5 <>
6 <Head>
7 <title>My Page Title</title>
8 <meta name="description" content="This is a description of my page." />
9 <meta name="keywords" content="nextjs, react, seo" />
10 <meta property="og:title" content="My Page Title" />
11 <meta property="og:description" content="This is a description of my page." />
12 </Head>
13 <h1>Welcome to My Page</h1>
14 </>
15 );
16}Importance for SEO :
Helps search engines understand the page content.
Improves search ranking and click-through rates.
Influences how pages appear when shared on social media.
Provides better accessibility and structured data for crawlers.
9. What is HMR (Hot Module Replacement) and how does it improve the development experience in Next.js ?
Hot Module Replacement (HMR) in Next.js is a development tool that enables the replacement of modules in the browser without requiring a full page reload. When you make changes to a file (component, CSS, and so on), Next.js will update only the modified module, leaving the state of the application unchanged whenever possible.
How HMR Improves Development Experience :
Faster feedback loop
Preserves component state
No need to manually refresh
Improves productivity
Better debugging workflow
10. What is prefetching and how does it work in Next.js ?
Prefetching in Next.js is a performance optimization feature that enables the application to load resources such as JavaScript, CSS, and data for a page before the user visits it. This is usually achieved through the use of the Link component from next/link, which automatically prefetches the linked page in the background when it comes into view in the viewport. This enhances navigation and user experience.
How Prefetching Works :
When a <Link> component appears in the viewport, Next.js automatically prefetches the code for that route (in production).
It downloads the page’s JavaScript bundle in the background.
When the user clicks the link, the page renders immediately without waiting for network requests.
11. What is the difference between Layout and Template in Next.js ?
In Next.js App Router, both layouts and templates are used to wrap pages with shared UI, but the main difference is that templates do not preserve state. Layouts are used when you want to share UI components like navigation bars or sidebars, whereas templates are used when you want a new instance of the UI to be created every time you navigate. Templates are re-rendered every time the route changes.
Layouts :
Persist across nested routes.
Maintain state and components (like headers, sidebars) while navigating between pages.
Useful for shared UI that should not reset on route changes.
Templates :
Do not preserve state between navigations.
Render fresh UI for each page visit, even if nested under the same layout.
Useful when the page should reset components or state on every render.
12. How do you handle environment variables in Next.js ?
In Next.js, environment variables are handled through .env files, which are automatically loaded into the application. Variables that should be used on the server side are kept private, while variables that should be accessible to the browser must be prefixed with NEXT_PUBLIC_. This is important for keeping sensitive information such as API keys private while ensuring safe variables are accessible on the client side.
Example
1DATABASE_URL=postgres://user:pass@localhost:5432/db
2 NEXT_PUBLIC_API_KEY=123456789013. How do you internalize Next.js app for multiple languages ?
Internationalization (i18n) in Next.js enables an application to support multiple languages by setting up language-based routing and translating content. Next.js supports i18n routing out of the box, and it can be integrated with libraries such as next-i18next for translation management. This makes it possible to have language-specific routes (e.g., /en, /fr) and easy language switching.
Advanced Interview Questions for Next Js
1. How do you handle authentication in Next.js ?
Authentication in Next.js can be achieved through JWT-based authentication, session-based authentication, or through libraries such as NextAuth.js. This choice of authentication strategy depends on whether authentication is done on the client side, server side, or both. Generally, authentication is done by storing a token in cookies or HTTP-only cookies, securing routes with middleware, and then authenticating the user on both the client and server sides.
2. How do you handle CORS when making API requests to different domains in Next.js ?
The CORS (Cross-Origin Resource Sharing) is handled by the server that receives the request. When a Next.js app is making API requests to another domain, the other server needs to allow the request by sending the right CORS headers. If you are not able to change the other API, you can use Next.js API routes as a proxy to make the request.
3. Describe scenarios where you would choose to use getStaticProps over getServerSideProps, and vice versa.
The decision between getStaticProps and getServerSideProps depends on how dynamic your data is and how often it changes in a Next.js application.
Use getStaticProps when :
Content is mostly static: If the data isn’t updated very often (like blogs, marketing sites, and documentation), pre-rendering pages during build time will provide outstanding performance and SEO because search engines can crawl the content easily.
Better scalability is needed: Since the pages are pre-rendered, the server doesn’t have to handle requests on every page visit, which means less load and lower hosting expenses.
Faster user experience: Since the pages are pre-rendered, they load instantly, providing a seamless and extremely responsive experience.
Use getServerSideProps when :
Content is updated constantly: If your data is constantly changing on every request (such as live news, stock market information, or dashboards), server-side rendering will ensure that users have access to the latest information available.
Personalization is required for users: For functionalities such as authentication, user dashboards, shopping carts, or role-based access, server-side rendering enables the creation of dynamic data on every request.
Real-time API or database connectivity: If you require the latest data from APIs or databases on every page load, getServerSideProps retrieves the data on every request.
4. What are some best practices for improving performance in Next.js app ?
To optimize the performance of a Next.js app, you can take advantage of the existing rendering techniques such as Static Site Generation, Server-Side Rendering, and Incremental Static Regeneration based on the type of content you are working with. You can also make use of automatic code splitting, dynamic imports, image optimization, caching, and performance analytics.
Use the Right Rendering Strategy : SSG → Best for static content (fastest performance), SSR → For frequently changing data and ISR → Static performance with periodic update
Code Splitting & Dynamic Imports
Image Optimization : Use the next/image component
Optimize Data Fetching
Use Middleware & API Routes Efficiently
Enable Caching & CDN
Monitor Performance
5. What are some common security considerations when using Next.js ?
When working with Next.js, some of the most important security concerns include XSS, CSRF, data leakage, API abuse, and vulnerabilities in dependencies. Because Next.js allows you to write both client-side and server-side code, it’s essential to properly secure both.
When working with Next.js, it’s essential to consider the following security concerns: cross-site scripting (XSS) and cross-site request forgery (CSRF). To protect against XSS, make sure you are properly sanitizing any user-supplied content and utilizing tools such as Next.js’s built-in next/script component to safely inject scripts. To protect against CSRF, you can utilize tokens to protect your API routes.
In addition, be careful with using environment variables. Avoid putting sensitive data on the client side; instead, utilize API routes or server-side code to handle sensitive tasks. Keep your dependencies up to date to prevent known vulnerabilities, and utilize Content Security Policies (CSP) to dictate what resources can be loaded on your site.
6. What is the purpose of publicRuntimeConfig and serverRuntimeConfig in Next.js ?
In Next.js, publicRuntimeConfig and serverRuntimeConfig are configuration options that are defined in next.config.js. They enable you to store values of runtime configuration with varying levels of visibility. The main difference between them and regular environment variables is the manner and location in which the values are made visible, especially in the context of the client and server.
publicRuntimeConfig
Purpose : publicRuntimeConfig is utilized for storing configuration values that must be accessible on both the server and the client. It is appropriate for storing non-sensitive information such as public API base URLs, themes for applications, or feature flags.
Accesibility : The values are included in the JavaScript bundle that can be accessed in React components.
Example :
1module.exports = {
2 publicRuntimeConfig: {
3 API_BASE_URL: 'https://api.example.com',
4 },
5 }serverRuntimeConfig
Purpose : serverRuntimeConfig is used to store sensitive values that should only be accessible on the server. These values are never exposed to the client bundle.
Security : deal for secrets such as database credentials or private API keys.
Example :
1// next.config.js
2module.exports = {
3 serverRuntimeConfig: {
4 secretKey: "super-secret-key",
5 },
6};7. How does Next.js optimize production builds internally ?
Next.js optimizes production builds using automatic code splitting, tree shaking, minification, and bundling through Webpack or Turbopack. Each page is split into its own JavaScript bundle so only required code loads per route. It also:
Removes unused code (tree shaking).
Minifies JavaScript and CSS
Optimizes images via next/image
Pre-renders pages using SSG or SSR
Enables automatic static optimization when possible
Prefetches linked pages in production
Generates optimized server and client bundles separately
This results in smaller bundle sizes, faster load times, and improved SEO.
8. How does Next.js manage caching with ISR and revalidation ?
With Incremental Static Regeneration (ISR), Next.js generates a static page at build time and revalidates it after a specified interval using the revalidate property.
Example :
1export async function getStaticProps() {
2 const data = await fetchData();
3 return {
4 props: { data },
5 revalidate: 60, // Revalidate every 60 seconds
6 };
7}How it works :
The page is generated at build time.
After 60 seconds, the next request triggers background regeneration.
Users get the old page while a new one is generated.
Future users receive the updated version.
9. What are Edge Functions and when would you use them in Next.js ?
Edge Functions run server-side logic closer to the user using the Edge Runtime (instead of a centralized Node.js server). They execute at CDN edge locations, reducing latency.
Use Cases :
Authentication and authorization
Geolocation-based content
A/B testing
Lightweight middleware logic
Request rewriting and redirects
10. How does Next.js differ in page router vs app router ?
Page Router :
Uses pages/ directory
File-based routing
Uses getStaticProps, getServerSideProps
Traditional data fetching model
Uses _app.js and _document.js
App Router :
Uses app/ directory
Built around React Server Components
Nested layouts by default
Supports streaming and suspense
Uses fetch with built-in caching
Uses layout.js, template.js, error.js
Key Differences :
Pages Router is client-centric with explicit data functions.
App Router is server-first with React Server Components and advanced caching.
11. How does Next.js handle hydration and what issues can arise ?
Hydration happens when React attaches event listeners to server-rendered HTML on the client. The server sends pre-rendered HTML, and React makes it interactive in the browser.
Issues that can arise :
Hydration mismatch errors (server HTML differs from client render)
Using browser-only APIs during SSR
Random values (Date.now, Math.random) during rendering
Conditional rendering differences
12. How would you design a scalable enterprise Next.js architecture ?
To design a scalable enterprise Next.js architecture, I would focus on modularity, performance, and maintainability. Key principles include :
Clear layered structure with separated folders for components, features, services (API logic), lib (utilities), hooks, and store (global state management)
Rendering strategy planning by using SSG for static content, ISR for semi-dynamic content, SSR for authenticated dashboards, and CSR for highly interactive components
API Layer Separation
State Management using Redux Toolkit or Zustand for global state, and React Query for server state
Caching Strategy
Security
Performance Optimization
CI/CD & Monitoring
Related Articles
Python Interview Questions
Master your Python interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.
FrontendJava Interview Questions
Prepare for your next tech interview with the most asked Java interview questions and answers. It includes basic to advanced concepts, coding problems, and real-world scenarios for freshers and experienced developers.