Posted in

Top 30 Next.js Interview Questions and Answers for All Experience Levels

Introduction

Next.js is a powerful React framework for building production-ready web applications. This blog post features 30 essential Next.js interview questions and answers, organized from basic to advanced. Ideal for freshers, developers with 1-3 years, and 3-6 years of experience preparing for roles at companies like Atlassian, Adobe, or Swiggy.

Basic Next.js Interview Questions

1. What is Next.js?

Next.js is a React framework that provides server-side rendering, static site generation, built-in routing, and API routes for full-stack development.

2. What are the main features of Next.js?

Key features include file-based routing, SSR/SSG support, automatic code splitting, API routes, image optimization, and TypeScript support out of the box.

3. How do you create a new Next.js project?

Use the command npx create-next-app@latest my-app to scaffold a new Next.js project with all default configurations.

4. What is the pages directory in Next.js?

The pages/ directory enables file-based routing where each file becomes a route. For example, pages/about.js creates the /about route.

5. What is the difference between pages and app directory in Next.js?

The pages/ directory uses the Pages Router with data fetching methods like getStaticProps. The app/ directory uses the App Router with React Server Components and server actions.

6. How do you enable TypeScript in Next.js?

TypeScript is enabled by default in new projects. Rename your files to .tsx or .ts and create a tsconfig.json if needed.

7. What are environment variables in Next.js?

Environment variables are stored in .env.local files. Prefix with NEXT_PUBLIC_ to access them on the client side.

8. How do you run a Next.js development server?

Use npm run dev or yarn dev to start the development server at http://localhost:3000.

9. What is the purpose of next.config.js?

next.config.js customizes Next.js behavior including webpack config, image domains, redirects, and custom headers.

10. How do you handle links in Next.js?

Use the <Link> component from next/link for client-side navigation:

<Link href="/about"><a>About</a></Link>

Intermediate Next.js Interview Questions

11. What is Static Site Generation (SSG) in Next.js?

SSG pre-renders pages at build time using getStaticProps. Pages are served as static HTML for optimal performance.

12. Explain getStaticProps with an example.

getStaticProps fetches data at build time. Example for fetching blog posts:

export async function getStaticProps() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();
  return { props: { posts } };
}

13. What is Server-Side Rendering (SSR) in Next.js?

SSR renders pages on each request using getServerSideProps. Ideal for dynamic content that changes frequently.

14. What is the difference between getStaticProps and getServerSideProps?

getStaticProps runs at build time (faster, cached). getServerSideProps runs on every request (dynamic, slower).

15. What is getStaticPaths and when is it used?

getStaticPaths is used with dynamic routes ([id].js) to define paths for SSG. It returns an array of path objects.

16. Explain the fallback property in getStaticPaths.

fallback: false shows 404 for undefined paths. fallback: true generates pages on-demand. fallback: 'blocking' serves after generation.

17. What are API Routes in Next.js?

API Routes in pages/api/ create serverless endpoints. Example pages/api/hello.js serves /api/hello:

export default function handler(req, res) {
  res.status(200).json({ message: 'Hello World' });
}

18. How do you implement dynamic routing in Next.js?

Create a file like pages/posts/[id].js. Access the ID via router.query.id or context.params.id in data fetching.

19. What is next/dynamic and how is it used?

next/dynamic enables code splitting and lazy loading:

const DynamicComponent = dynamic(() => import('../components/Heavy'), { loading: () => <p>Loading...</p> });

20. How do you optimize images in Next.js?

Use the <Image> component from next/image which provides automatic optimization, lazy loading, and responsive sizes.

Advanced Next.js Interview Questions

21. What is Incremental Static Regeneration (ISR)?

ISR allows updating static pages after build using the revalidate property in getStaticProps: return { props: {}, revalidate: 10 }.

22. How does middleware work in Next.js?

Create middleware.js in the root to run code before requests complete. Used for authentication, redirects, and headers.

23. Explain React Server Components in Next.js App Router.

Server Components run only on the server, reducing client bundle size. They can’t use browser APIs or hooks like useState.

24. What are Server Actions in Next.js 13+?

Server Actions are async functions marked "use server" for handling form submissions directly on the server without API routes.

25. How do you implement authentication in Next.js?

Use JWT tokens stored in HTTP-only cookies. Protect routes with middleware checking valid tokens before allowing access.

26. What is the purpose of next/script?

next/script optimizes third-party scripts with strategies like afterInteractive, lazyOnload to improve loading performance.

27. How do you handle errors in Next.js App Router?

Create error.js and not-found.js in the same directory as your page components to handle route-specific errors.

28. Explain performance optimization techniques in Next.js.

Techniques include code splitting with dynamic imports, ISR/SSG, image optimization, caching API responses, and using Lighthouse for audits.

29. How do you prevent hydration errors in Next.js?

Avoid mismatched server/client HTML by using useEffect for browser-only code, dynamic imports with ssr: false, and proper conditional rendering.

30. What security practices should you follow in Next.js?

Validate/sanitize inputs, use HTTP-only cookies for tokens, configure security headers in next.config.js, and protect API routes from unauthorized access.

Leave a Reply

Your email address will not be published. Required fields are marked *