Next.js Interview Questions



In this article, we have made a list of Next.js interview questions that will help you prepare for your Next.js job interview. These questions cover basic, medium, and advanced topics related to Next.js development.

Interview Questions and Answers on Next.js Framework

This list of Next.js interview questions will cover all the important topics related to Next.js development. These questions are suitable for both freshers and experienced developers who are preparing for a Next.js job interview. If you are a fresher, you can start covering basic questions first and then move on to medium and advanced questions. If you know something about Next.js or have some experience, you can start with medium or advanced questions.

Basic Questions

1. What is Next.js and how is it different from React?

Next.js is a React Based web development framework with server side rendering capability to create full stack web apps. It is built on top of React and Node.js and provides a set of features that make it easier to develop and deploy web applications.

React on the other hand, is a JavaScript library for building user interfaces. React is developed by Facebook and Next.js is developed by Vercel. Next.js uses React under the hood and provides additional features to make web development easier.

2. Mention some key features of Next JS.

Some of the key features of Next.js are:

  • Server-side rendering: Next.js uses server-side rendering to generate HTML on the server and send it to the client. This allows for faster initial page load as JavaScript is not required.
  • Static site generation: Next.js supports static site generation, which means that pre build HTML files are generated at build time.
  • API Routes: Next.js allows you to create API routes, making it easier to create serverless functions that can be called from your Next.js application.
  • File based routing: Next.js supports file based routing, which means that you can create routes based on the file structure of your application.
  • Optimization For SEO: Next.js provides several optimization techniques to improve the performance of your web application for search engines.
  • Automatic code splitting: Next.js automatically splits your code into smaller chunks, which reduces the initial load time of your application.

3. How to set up a Next.js project?

To create a Next.js application, open your terminal/powershell in the folder where you want to build app. Then run the following command (same for mac/linux/windows).

npx create-next-app@latest

After running this you will be prompted to give name for your project. Enter a suitable name, and then you will be asked to select tools to be installed along with Next.js. Using left arrow, right arrow and enter key, select Typescript, Tailwind CSS and ESlint. Use the image below as reference.

Next-js-installation

After successfully creating a new Next.js app, you can see a new folder with lots of file in the directory you selected. Now in the terminal, navigate to the project directory and run dev server. Use the following command. (Replace name of your app in command)

// navigate to the project directory
cd next-js-example

// Run the dev server
npm run dev

On successfully running this command, a new Next.js server will be set up at 'http://localhost:3000/'. Your default browser will open this page automatically for you.

4. Explain Next.js project structure?

Next.js project structure is based on routing system, which means any file inside the pages/ or app/ directory determines the application routes automatically. Following diagram shows basic structure of Next.js App router project.

nextjs-app-router/
     app/                      // Root folder for App Router
        counter/              // Folder for Counter Page
           page.tsx
        page.tsx
     public/ 
     next.config.js
     package.json
     middleware.ts
     .env
     .env.local
     .gitignore

For example,

  • app/page.tsx : This is home page of Next.js app. It can be accessed by 'localhost:3000/'
  • app/counter/page.tsx : This define a component section in app. It can be accessed by 'localhost:3000/counter'

5. How do you handle CSS in Next.js

Next.js have built-in support for CSS. You can use CSS modules, global styles, and Tailwind CSS to style your application. Following are the ways to handle CSS in Next.js.

  • Module Specific Styles: You can define styles for a specific component/module using .module.css extension. The style specified by this method will not affect any other components. In Next.js module, you can use "styles.className" or "styles.idName" to get class or id names from CSS file.
  • Global Styles: You can define global styles for Next.js applications using the /app/globals.css file. This file is imported by all pages in the application and hence the style defined here will be applied to all pages.
  • Tailwind CSS Support: Next.js supports Tailwind CSS out of the box. You will be asked to include Tailwind CSS in your project when you create a new Next.js application.

6. How do you use global styles in a Next.js application?

Next.js provide built-in global css file in your application setup. If you are using App router for your Next.js project, you will already have global.css file in project's app folder. For page router you can find global css file inside the styles folder. For example, the code below is a global CSS file.

// /app/global.css

h1 {
    color: #0070f3;
}

div {
    font-family: Arial, sans-serif;
    max-width: 400px;
}

Importing of global CSS is done at layout component. This is a special component, that is visible in every routes and style applied to this component will applicable to all other components.

// app/layout.tsx

import './/globals.css'; // import CSS

interface RootLayoutProps {
  children: ReactNode;
}

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <html lang="en">
        <body>
            <header>
                <h1>Header Element</h1>
            </header>
            <main>{children}</main>
        </body>
    </html>
  );
}

7. Explain the concept of routing in Next.js?

Routing is a mechanism by which an application determines how to handle and respond to various URLs or user navigation requests. Routing in Next.js is based on file systems in project directory. This means the structure of your application files defines the structure of your routes.

Next.js uses a file-system based routing where:

  • Folders are used to define routes. A route is a single path of nested folders, following the file-system hierarchy from the root folder down to a final leaf folder that includes a page.js file.
  • Files are used to create UI that is shown for a route segment.

8. What are App Router and Page Router in Next.js?

App router and page router are two different routing approaches in Next.js.

  • App Router(Next.js 13+): App router is a modern routing approach using /app directory. It offers advanced features like React Server Components, nested routing, and enhanced server-side rendering. App router is the recommended approach for new projects.
  • Page Router (Next.js 12 and earlier): Page router is traditional approach of routing using /pages directory. It is simpler and less flexible than app router, but it is still widely used.

9. Explain the concept of static site generation in Next.js

Static Site Generation is a server rendering strategy where the application generate HTML pages at the time of building application. That means, when you build the application for production, the HTML pages are generated and cached in the build folder. This is the default strategy for Next.js applications.

  • In Static Rendering, a HTML page is built once, which then cached by CDN and severed to the client almost instantly.
  • This type of rendering improves performance and user experience of the application.
  • By default all the Next.js components that does not involve fetching data from external source follows static rendering strategy.
  • Static rendering is commonly used in blog pages, documentation pages, and marketing pages.

10. What are environment variables? How to load it in Next.js?

Environment variables are used to store sensitive information like API keys, database passwords, and other secrets. They are loaded from the .env file in the root directory of the project.

For example, you can create a .env file in the root directory of your project and add API keys like this:

// File: /.env

API_KEY=djcjcwj-wcdkjcnw

Next.js will automatically load the API key defined in this file and make it available in the process.env object. You can access the API key using the following code:

console.log(process.env.API_KEY)

11. What is the purpose custom <Image> component in Next.js?

In Next.js, the <Image> component is used to load optimized images in application. It extends the HTML <img> element to provide extra features to optimize images, improve image loading time, and handle imageNotFound error.

Following code shows syntax for basic usage of <Image> component in Next.js.

import Image from 'next/image' // Import library
 
export default function Page() {
  return (
    <div>
        <Image
            src = "/link/to/image"
            width = {width}
            height = {height}
            alt = "alternative name"
        />
    </div>
  )
}

12. What is <Link> component in Next.js?

In Next.js, the <Link> component is used to create links between pages just like the <a> tag in HTML. It is used to navigate between pages and handle client-side navigation. The link component is a wrapper around the <a> tag and provides additional features such as prefetching, preloading, and automatic code splitting. Following code shows implementation of <Link> component in Next.js.

// Import the library
import Link from 'next/link'

export default function Page() {
    return (
        // Navigate to /about page
        <Link href="/about">
            About
        </Link>
    )
}

Learn more about link component.

13. What is the difference between client-side and server-side rendering?

Client-side rendering (CSR) is the process of generating HTML on the client's browser using JavaScript. On the other hand, server-side rendering (SSR) is the process of generating HTML pages on server and sending them to the client. The following table summarizes the differences between CSR and SSR:

Criteria Client-side Rendering Server-side Rendering
Rendering HTML is generated in the browser using JavaScript. HTML is generated on the server and sent to the browser fully rendered.
Initial Load Time Slower initial load as JavaScript needs to be downloaded and executed. Faster initial load since the browser receives a fully rendered page.
SEO Not ideal for SEO as search engines may struggle with JavaScript-rendered content. Better for SEO because the content is fully rendered and accessible to search engines.
Interactivity Highly interactive; changes can be made dynamically without reloading the page. Less interactive by default; requires a page reload for updates unless enhanced with additional scripts.
Performance Faster for repeat visits due to reduced server dependency and caching. Faster for initial visits, but may require more server resources for each request.
Complexity Requires a front-end framework like React, Angular, or Vue.js for rendering. Can be implemented with traditional server-side technologies like PHP, Python, or Node.js.

14. Explain prerendering and types of prerendering in Next.js

Pre-rendering is a technique used in Next.js for generating HTML pages in advance, instead of serving a blank HTML page and waiting for JavaScript to render the content on the client side. By default, Next.js pre-renders every page. The process of loading JavaScript to pre-rendered HTML page is called hydration.

  • Pre-rendering reduces the interacting time by delivering ready-to-use HTML.
  • Search engines can crawl pre-rendered content more easily.
  • Pre-rendering give better user experience.
  • In Next.js, we have two types of pre-rendering:

    15. What is partial pre-rendering in Next.js?

    Partial Pre-rendering (PPR) is a rendering pattern in Next.js that combines static and dynamic content in a single page. The static contents along with static fallback for dynamic contents will be pre-rendered at the build time. The dynamic contents will be rendered as per request from user. This method ensures a faster initial page loads as the static content is pre-rendered, and results in better SEO and user experience. Learn more about Partial Pre-rendering in Next.js

    Medium Level Questions

    16. What is styled-jsx in Next.js?

    The styled-jsx is a CSS-in-JS library that allows you to write CSS directly in your JavaScript code.Next.js have built-in support for styled-jsx. By this, you can style components with scoped CSS and without additional dependencies. Following is code for styled JSX in Next.js home page.

    'use client';
    
    export default function Home() {
      return (
        <div>
          <style jsx>{`
            h1 {
                color: green;
            }
          `}</style>
        </div>
      );
    }
    

    Learn more about styled-jsx in Next.js.

    17. What are API routes in Next.js?

    API Routes in Next.js are serverless functions for handling API requests. These routes enable you to define server-side logic that can be called from the frontend or any external client. The API routes are mostly used for handling requests like fetching data, submitting forms, or implementing server-side operations.

    • API Routes in Next.js are created by adding a typescript file inside the 'pages/api' directory.
    • The file name becomes the endpoint of the API.
    • Any file inside the folder 'pages/api' is mapped to /api/* and will be treated as an API endpoint instead of a page.
    • For example, if you create a file named 'hello.js' inside the 'pages/api' directory, the endpoint will be '/api/hello'.

    18. How to programmatically redirect routes in Next.js?

    Next.js provide inbuilt methods and APIs for handling redirecting of routes in application. Following are three methods to implement redirecting in Next.js.

    • useRouter hook is used to redirect or navigate routes at client side. This hook can only be used in client side components. This is useful when we want redirect user to home page or any other page after clicking a button or submitting a form.
    • redirect() method: The redirects option in the next.config.js file allows you to redirect an incoming request path to a different destination path. This is useful when you change the URL structure of pages or have a list of redirects that are known ahead of time.
    • NextResponse.redirect: Redirect an incoming request based on a condition. This method is used in middleware to redirect user to a different page based on certain condition.

    19. Define imperative routing and shallow routing in Next.js?

    Imperative routing is a method of navigating programmatically based on certain condition or user action such as clicking button. This approach is particularly useful when navigation depends on user authentication status, dynamic condition and custom business logic.

    Shallow routing is a routing method in Next.js in which the URL update occur without re-rendering or reloading the entire page. This method avoid re-executing of data fetching methods like getServerSideProps, getStaticProps, and getInitialProps. It provides a way to modify the URL and route state without losing the current page's context or performance.

    20. What are the performance optimization techniques in Next.js?

    Next.js comes with a variety of built-in optimizations designed to improve your application's speed and Core Web Vitals. Following are commonly used optimization techniques in Next.js:

    • Optimize Memory Usage Next.js have built-in tools to monitor memory usage of the application, use these tools to identify memory leaks and optimize memory usage.
    • Implement Lazy Loading: Lazy Loading is optimization technique to control the loading of non-critical resources.
    • Optimize Images Rendering Next.js provides a built-in <Image> component to optimize images in webpage. Using this instead of <img> tag will automatically optimize performance of image loading.
    • Reduce JavaScript Bundles Next.js application may contain lots of JavaScript files that are not useful for the initial page load. You can activate tree shaking to optimize the bundle size.
    • Optimize Script Loading Next.js provides a built-in <Script> component to optimize script loading in webpage. Using this instead of <script> tag will automatically optimize performance of script loading.

    21. What is middleware? Why it is used in Next.js?

    Middlewares are reuseable functions executed before the main request handler logic. These functions are commonly used for tasks like authentication, logging, rate limiting, input validation, or other pre-processing tasks. Middleware will help you centralize common logic and ensure consistency across multiple API routes.

  • Pre-Processing Request: Middleware functions allow you to inspect, modify, or validate the incoming request before passing it to the main handler.
  • Centralized Logic: Middleware helps to reduce code duplication by defining middleware logic once and reuse it across multiple API routes.
  • Early Termination: Middleware can terminate a request early (e.g., if authentication fails) to prevent further processing.
  • 22. How do you create a hybrid rendering approach in Next.js?

    Hybrid rendering is a technique that combines server-side rendering (SSR) and client-side rendering (CSR) to provide the best of both worlds. In Next.js, you can create a hybrid rendering approach by using getServerSideProps for server-side rendering and useEffect for client-side rendering. This allows you to pre-render the page on the server and then hydrate it on the client, providing a fast initial load time and interactive experience.

    Learn more about hybrid rendering.

    23. How do you implement authentication in a Next.js application?

    Authentication is the process of verifying the identity of a user. In Next.js, you can implement authentication using various methods such as cookies, sessions, JSON Web Tokens (JWT), OAuth, and more. In general, there are three steps to implement authentication in a Next.js application:

    • Take user's credentials: Create a form to take the user's credentials, such as email and password.
    • Validate the credentials: Validate the user's credentials on the client side to ensure they are in the correct format.
    • Verify the credentials with the server: Send the user's credentials to the server to verify them against the database and authenticate the user.

    Learn more about authentication in Next.js.

    24. What is lazy loading in Next.js?

    Lazy Loading is a technique used in web applications by which the app delays loading of non-critical resources until they are actually needed. This method helps improve the initial loading performance of an application by decreasing the amount of JavaScript needed to render a route.

    • First, Next.js will split the code into separate bundles at build time.
    • When a user navigates to a route that requires a specific bundle, the app will load that bundle only when it is needed.
    • The images, components, and other modules are loaded only when they become visible in the viewport

    25. Explain how to implement dynamic routing in Next.js?

    Dynamic routing in Next.js allows to create flexible and reusable routes based on the user's input. This feature is essential when building applications where the routing page depends on user input, database records, or other dynamic data. For example, if you want to generate a dynamic page based on the what user selected, you can use dynamic routing.

    To create a dynamic route for a product page, start by creating a folder named "products" inside the `/app/` directory. Then, inside the "products" folder, create another folder named `[id]` and add `page.tsx` file inside it. The square brackets `[id]` indicate that this folder represents a dynamic route and the name can be changed based on the product selected by the user.

    // app/products/[id]/page.tsx
    
    "use client"
    import { useParams } from 'next/navigation';
    
    export default function ProductPage() {
      const { id } = useParams();
    
      return (
        <div>
          <h1>Product {id}</h1>
          <p>This is the product page for item {id}.</p>
        </div>
      );
    }
    

    26. How to create custom Metadata for each pages in Next.js?

    The custom metadata or dynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata in parent segments. It can be set by exporting a generateMetadata() function that returns a Metadata object. In the code below, we will generate a dynamic title for a component based on the page selected by the user.

    // app/products/[id]/page.tsx
    
    import { Metadata } from "next";
    
    type Props ={
        params: {
            id: string;
        };
    }
    // Dynamic Metadata function
    export const generateMetadata = ({ params }: Props): Metadata => {
        return {
            title: `Product ${params.id} - My Store`,
        };
    }
    
    export default function ProductPage({params }: Props) {
    
        return (
            <div>
                <h1>Product {params.id}</h1>
                <p>This is the product page for item {params.id}</p>
            </div>
        );
    }
    

    27. What is incremental static regeneration (ISR)?

    Incremental Static Regeneration (ISR) is a feature in Next.js that allows you to update static pages at runtime without rebuilding the entire site. This feature is useful for pages that need to be updated frequently, such as blog posts, product listings, or news articles. With ISR, you can set a revalidate time for each page, which determines how often the page should be regenerated. When a user requests a page that is stale, Next.js will serve the cached page while regenerating the new page in the background. Once the new page is ready, it will be served to subsequent users.

    28. What is next.config.ts file? Explain it's properties.

    The next.config.ts file is a configuration file in Next.js. It is used to customize the behavior of the Next.js application, such as setting up environment variables, configuring webpack, adding plugins, and more.

    • excludes property: The excludes property in the next.config.js file is used to specify patterns for files and directories that should be excluded from the automatic code splitting and bundling performed by Next.js. By defining exclusion patterns, developers can control which files are not subject to the default behavior of code splitting.
    • headers property: The headers property in the next.config.js file is used to define custom HTTP headers that should be included in the responses served by your Next.js application. This property allows developers to set various HTTP headers, such as caching policies and security-related headers
    • redirects property: The redirects property in the next.config.js file is used to define a list of URL redirects that should be applied to incoming requests. Redirects are used to map an incoming request path to a different destination path, allowing developers to manage changes to the URL structure of their application or implement custom routing logic.

    29. What is the purpose of _app.js file?

    The `_app.js` file serves as the pivotal component for the entire Next JS application. It provides the flexibility to override the default App component supplied by Next JS, enabling customization of the application's behavior across all pages. Typically utilized for tasks such as incorporating global styles, persisting layout components, or initializing third-party libraries.

    30. What are Next.js CLI command?

    Next.js CLI commands are used to perform various tasks such as creating a new Next.js project, running the development server, building the application for production, and more. Some common Next.js CLI commands include:

    Commands Explanation
    dev The dev command starts Next.js application in development mode with hot module reloading and error reporting features.
    build This creates an optimized production build for the application.
    start Starts the Next.js application in production mode. The application should be built before starting production mode.
    info This is used to print relevant information about the current system, which can be used to report Next.js bugs.
    lint The Lint command runs ESLint for all files in the Next.js directories. It also provides a guided setup to install any required dependencies if ESLint it is not already configured in your application.
    telemetry This is used to enable or disable sharing telemetry data about general usage with Next.js.

    31. How to change the default development port in Next.js CLI?

    To change the default port, you can use the `dev` command along with port number. Following is syntax to change default port number.

    >> npx next dev -p 4000
    

    After running the above command in your terminal, Next.js development mode will start running on `http://localhost:4000/`. Your default browser will open the page automatically. See the image for reference.

    next.js-change-default-port

    32. How to start Next.js server on custom hostname?

    We can use the start command to specify a custom hostname for the production server. Following is an example syntax:

    >> npx next start -H 127.0.34.1
    

    After running the above command in your terminal, the Next.js production server will start running on `http://127.0.34.1:3000/`.

    next.js-start-host

    33. How to use secure protocol in Next.js dev environment?

    By default, Next.js uses unsecure HTTP protocol for developmental purposes. However, for testing certain features like webhooks or authentication, you can use HTTPS to have a secure environment on localhost. Next.js can generate a self-signed certificate with next dev using the --experimental-https flag. Following is the syntax for command.

    >> npx next dev --experimental-https
    

    When running the above command, Next.js uses `mkcert` to generate self-signed certificates for local development. This will create a CA root certificate stored in the directory.

    next.js-https-connection

    34. How to enable TypeScript in Next.js project?

    Next.js comes with built-in TypeScript support. When you create a new Next.js project, you will be asked to include TypeScript in your project. Choosing to include typescript will automatically installing the necessary packages and configuration for TypeScript support. To add TypeScript to an existing project, rename a file to .ts or .tsx. Then run 'next dev' and 'next build' to automatically install the necessary dependencies and add a tsconfig.json file with the recommended config options.

    Next-js-TypeScript-Support

    The above images shows setting up Next.js using create-next-app command. You can see that it asks to include TypeScript in the project.

    35. How to create custom 404 page in Next.js?

    Next.js provides a built-in mechanism to create a custom 404 page for your application. To create a custom 404 page, you need to create a file named `404.tsx` in the `/pages` directory of your Next.js application. The content of this file will be displayed when a user navigates to a page that does not exist.

    // pages/404.tsx
    
    export default function Custom404() {
      return <h1>404 - Page Not Found</h1>
    }
    

    Advanced Level Questions

    36. Explain advanced routing techniques in Next.js

    Routing is a mechanism by which an application determines how to handle and respond to various URLs or user navigation requests. Advanced routing techniques used in Next.js are

    Dynamic routing determine routes based on user interaction. To create a dynamic route for a product page, start by creating a folder named "products" inside the `/app/` directory. Then, inside the "products" folder, create another folder named `[id]` and add `page.tsx` file inside it. The square brackets `[id]` indicate that this folder represents a dynamic route and the name can be changed based on the product selected by the user.

    // app/products/[id]/page.tsx
    
    "use client"
    import { useParams } from 'next/navigation';
    
    export default function ProductPage() {
      const { id } = useParams();
    
      return (
        <div>
          <h1>Product {id}</h1>
          <p>This is the product page for item {id}.</p>
        </div>
      );
    }
    

    Catch-All routes are a type of dynamic routes that matches with all the slugs in current route. For example, '/app/products/[...slug]/index.js' will match with,

    • /products/smartphones
    • /products/electronics/laptop
    • /products/beauty-products/ladies/lipstick

    To implement catch-all routing, define a directory square bracket directory with name starting with three dots. For example, [...productsSlug]. See the example below.

    // app/products/[...slug]/page.tsx
    
    export default function ProductPage({ params }: { params: { slug: string[] } }) {
      // This route will match /products, /products/electronics, /products/electronics/laptops
      return (
        

    Product Page

    Matched Segments: {params.slug?.join(' / ') || 'No segments'}

    ); }

    37. What is Tree Shaking Enhancement in Next.js?

    Tree shaking is automatic optimization technique used by Next.js to eliminate unused dead code from application. This technique will help to reduce the size of the JavaScript bundle, which in turn improves the performance of the application. The key aspects of tree shaking enhancement in Next.js are:

    • Automatic code elimination for unused exports
    • Reduced client-side JavaScript payload
    • Improved application performance

    38. How to implement pagination in Next.js?

    Pagination is a common feature in web applications that allows users to navigate through a large set of data or content in smaller, more manageable chunks. In Next.js, you can implement pagination by using query parameters to control the number of items displayed on a page and the current page number. You can use the useRouter hook to access the query parameters and update the page content based on the user's input.

    import { useRouter } from 'next/router';
    
    export default function Page() {
      const router = useRouter();
      const page = router.query.page || 1;
    
      return (
        <div>
          <h1>Page {page}</h1>
          <p>This is page {page} of the content.</p>
        </div>
      );
    }
    

    39. How to implement serverless functions in Next.js?

    Serverless functions are small, single-purpose functions that run in a serverless environment. In Next.js, you can create serverless functions using API routes. API routes are serverless functions that handle API requests and can be used to fetch data, process forms, or perform other server-side operations. To create a serverless function in Next.js, create a file inside the `/pages/api` directory with the desired endpoint name. The file should export a default function that takes a request and response object as arguments.

    For example, let's create an API route that returns a JSON response. Create a file named 'hello.js' inside the 'pages/api' directory with the following code:

    // File: pages/api/hello.js
    
    export default function handler(req, res) {
      res.status(200).json({ message: 'Hello, Next.js API!' });
    }
    

    Now, if you visit the URL '/api/hello', you will see the following JSON response:

    Next.js API Routes

    40. How to implement webhooks in Next.js?

    Webhooks are a way for web applications to communicate with each other in real-time. In Next.js, you can implement webhooks using API routes. API routes are serverless functions that handle API requests and can be used to receive and process webhook notifications. To implement a webhook in Next.js, create a file inside the `/pages/api` directory with the desired endpoint name. The file should export a default function that takes a request and response object as arguments.

    41. How to write Jest test cases in Next.js?

    Jest is a popular JavaScript testing framework used to write tests for React applications, including Next.js. To write test in Jest, you need to setup Jest in your Next.js project. You can then write test cases for your components, pages, and utilities using Jest's testing utilities such as describe, it, expect, and more.

    After setting up Jest, create a test file for the Home component in the __tests__ directory. The test file should end with '.test.tsx' or '.test.jsx' extension. In the following code, we are testing if the above Home component renders the welcome message and if the button click triggers the alert function.

    // File - /__tests__/Home.test.tsx
    
    import { render, screen, fireEvent } from '@testing-library/react';
    import Home from '@/pages/index';
    
    describe('Home Page', () => {
        it('renders welcome message', () => {
            render(<Home />);
            expect(screen.getByText('Welcome to Next.js')).toBeInTheDocument();
        });
    
        it('handles button click', () => {
            render(<Home />);
            const alertMock = jest.spyOn(window, 'alert').mockImplementation();
            
            fireEvent.click(screen.getByText('Click Me'));
            expect(alertMock).toHaveBeenCalledWith('Hello!');
            
            alertMock.mockRestore();
        });
    });
    

    42. Explain the concept of code splitting in Next.js.

    Code splitting is a technique used to split your JavaScript bundle into smaller chunks that can be loaded on demand. This helps reduce the initial load time of your application by only loading the code that is needed for the current page. In Next.js, code splitting is done automatically using dynamic imports. When you use dynamic imports, Next.js will split your code into separate bundles based on the routes and components in your application. This allows Next.js to load only the code that is needed for the current page, improving performance and user experience.

    43. Explain techniques of caching in Next.js.

    Caching is a technique used in web applications to store data in server memory or on client browser so that it can be accessed quickly. Caching is used to reduce load times, improve performance, and reduce server load. Next.js provides several caching mechanisms to store cache data on the server and client side. Here are some of the caching mechanisms available in Next.js:

    • Request Memoization is used to re-use data in a React Component tree by automatically duplicating identical data requests during the same render cycle, preventing duplicate data fetching.
    • Data Cache is used to store results of fetch requests on the server and re-use it across multiple pages. This cache persists across multiple user requests and server renders.
    • Full Route Cache is used to cache the entire HTML page on the server and serve it to the client.
    • Router Cache is used to cache the entire page on the client side and serve it to the user. This cache will enable instant back/forward navigation.

    44. How to implement internationalization in Next.js?

    Internationalization (i18n) is the process of adapting a website or application to different languages and regions. In Next.js, you can implement internationalization using the next-i18next library, which provides tools and utilities for managing translations, language detection, and other i18n features. To implement internationalization in Next.js, follow these steps:

    • Install the next-i18next library using npm or yarn.
    • Configure the i18n settings in your Next.js application.
    • Create translation files for each language you want to support.
    • Use the i18n tools and utilities provided by next-i18next to manage translations and language detection in your application.

    45. What is AMP mode? How to enable it in Next.js?

    AMP (Accelerated Mobile Pages) is an open-source framework developed by Google to create fast-loading web pages for mobile devices. AMP pages are optimized for speed and performance, providing a better user experience on mobile devices. In Next.js, you can use, useAmp() hook to enable AMP mode for a specific page. Following is syntax of useAmp method.

    // Import the library
    import { useAmp } from 'next/amp';
    
    export const config = { amp: 'hybrid' };  
    
    export default function Home() {
        const isAmp = useAmp();
    }
    
    • The useAmp hook is typically used within a React component on pages that support AMP, so that you can conditionally render content based on whether the page is in AMP mode or not.
    • This method is only supported in pages router, in App router you can implement AMP functionality with the new server-side data fetching methods.
    • The AMP have two mode, AMP-only mode means the pages are exclusively rendered in AMP format and Hybrid-AMP mode means the pages are rendered in both AMP and standard modes, depending on the URL.

    46. What is metadata object in Next.js? Explain it attributes.

    In Next.js, the metadata object is part of the App Router used to define metadata for each route. With metadata object, we can define title, description and other SEO components even for dynamically generated routes. Here is syntax of metadata object.

    export const metadata = {
        title: "Title of Webpage",
        description: "Description of Webpage"
    }
    

    The title attribute is used to set the title of the document. It can be defined as a simple string or an optional template object.

    import type { Metadata } from 'next'
     
    export const metadata: Metadata = {
      title: {
        default: '...', 
        template: '...', 
        absolute: '...', 
      },
    }
    
    • default : This default title value, that define fallback title to child routes
    • template : Used to add a prefix or a suffix to titles defined in child routes
    • absolute : Used to provide a title that ignores title.template set in parent route.

    47. How to include custom fonts in Next.js?

    The 'next/font' package provides utilities to load Google Fonts and custom fonts with automatic optimizations. Next js will ensure fonts are automatically preloaded and optimized to reduce render-blocking requests, which results in better performance. The code below demonstrates how to include custom fonts in Next.js using the localFont utility.

    import localFont from 'next/font/local';
    
    // Configure the local font
    const myFont = localFont({
        src: './path/to/font.woff2',  // Path to the font file
        weight: '400',               // Optional weight
        style: 'normal',             // Optional style
    });
    
    export default function Home() {
        return (
        <div className={myFont.className}>
            <h1>Hello, Next.js with Inter font!</h1>
        </div>
        );
    }
    

    48. What is Request Memoization? Explain advanced memoization with parameters.

    Request memoization is a caching technique used in web applications to prevent duplicate data fetches during the same render cycle. This is used to improve performance and reduce load times by storing data in server memory or on client browser so that it can be accessed quickly.

    • Request memoization is a React feature, not a Next.js feature.
    • Memoization only applies to the GET method in fetch requests.
    • Memoization applies to fetch requests in generateMetadata, generateStaticParams, Layouts, Pages, and other Server Components.
    • Memoization doesn't apply to fetch requests in Route Handlers as they are not a part of the React component tree.
    • The memoization cache lasts the lifetime of a server request until the React component tree has finished rendering.

    Advanced memoization with parameters is used to memoize data based on specific parameters. In the following example, we have a function `getUser()` that fetches user data from an API endpoint. We are calling the function thrice with the same parameter, but the fetch request is only made twice. The second call uses the cached data from the first call.

    // app/dashboard/page.tsx
    interface User {
        id: string;
        name: string;
        email: string;
    }
    
    async function getUser(id: string): Promise<User> {
        const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
        if (!res.ok) throw new Error('Failed to fetch user');
    
        return res.json();
    }
    
    export default async function DashboardPage() {
        console.log('Starting fetches...');
    
        const startTime = Date.now();
    
        // These calls will demonstrate memoization
        const user1 = await getUser('1');  // First fetch
        console.log('First user1 fetch completed:', Date.now() - startTime, 'ms');
    
        const user1Again = await getUser('1');  // Memoized
        console.log('Second user1 fetch completed:', Date.now() - startTime, 'ms');
    
        const user2 = await getUser('2');  // New fetch
        console.log('User2 fetch completed:', Date.now() - startTime, 'ms');
    
        return (
            <div>
            <h1>User Dashboard</h1>
            <div>
                <h2>User 1 (First Fetch):</h2>
                <pre>{JSON.stringify(user1, null, 2)}</pre>
                
                <h2>User 1 (Memoized):</h2>
                <pre>{JSON.stringify(user1Again, null, 2)}</pre>
                
                <h2>User 2 (Different Fetch):</h2>
                <pre>{JSON.stringify(user2, null, 2)}</pre>
            </div>
            </div>
        );
    }
    

    49. How to implement server-side data fetching in Next.js?

    Server-side data fetching is a technique used in Next.js to fetch data from an external API or database on the server before rendering the page. This allows you to pre-fetch data and pass it to the page as props, improving performance and SEO. In Next.js, you can implement server-side data fetching using the getServerSideProps function. The getServerSideProps function is a special function that runs on the server before rendering the page and can fetch data from an external API or database.

    50. How to create an authentication middleware in Next.js?

    Authentication middleware is a function that runs before the main request handler to verify the user's identity and grant access to protected routes. We can create a simple authentication middleware that checks if the request contains a valid API key. Create a file named 'authMiddleware.js' inside the 'middlewares' directory with the following code:

    // File: middlewares/authMiddleware.js
    
    export default function authMiddleware(handler) {
        return (req, res) => {
          const headerApiKey = req.headers.apikey;
          const queryApiKey = req.query.apiKey;
    
          // Check if API key is present in header or query
          if ( (!headerApiKey && !queryApiKey) || 
                 (headerApiKey !== process.env.API_KEY && 
                 queryApiKey !== process.env.API_KEY) ) {
            return res.status(401).json({ message: 'Unauthorized' });
          }
          return handler(req, res);
        };
    }
    

    Now, let's use the authentication middleware in an API route. Create a file named 'hello.js' inside the 'pages/api' directory with the following code:

    // File: pages/api/hello.js
    
    import authMiddleware from '../../middlewares/authMiddleware';
    
    export default authMiddleware(function handler(req, res) {
        res.status(200).json({ message: 'Hello, Next.js API!' });
    });
    

    We have added an API key "djcjcwj-wcdkjcnw" to '.env.local' file in root folder. Now, if we visit the URL '/api/hello', an unauthorized response will be returned. But when we visited '/api/hello?apiKey=djcjcwj-wcdkjcnw', the API key is validated and the proper response is returned.

    Next.js API Middleware
    Advertisements