71. How can you control cache headers in Next.js?
Next.js allows you to control cache headers for static assets, dynamic routes, and API routes via next.config.js
and custom headers in getServerSideProps
or API routes.
-
Static assets: Next.js handles caching for static assets in the
public/
folder automatically, but you can customize cache headers usingheaders()
innext.config.js
.
module.exports = { async headers() { return [ { source: '/(.*)', headers: [ { key: 'Cache-Control', value: 'public, max-age=31536000, immutable', }, ], }, ]; }, };
-
Dynamic pages: For dynamic pages generated at runtime, you can set cache headers in the
getServerSideProps
function.
export async function getServerSideProps() { const res = await fetch('<https://api.example.com/data>'); const data = await res.json(); return { props: { data }, headers: { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=30', }, }; }
-
API routes: You can set cache headers in API routes to control how responses are cached.
export default function handler(req, res) { res.setHeader('Cache-Control', 'public, max-age=3600, s-maxage=3600'); res.json({ data: 'example' }); }
72. How do you test a Next.js application?
Testing a Next.js application involves using tools like Jest, React Testing Library, and Cypress for end-to-end tests.
-
Unit tests: Use Jest and React Testing Library to test components and hooks.
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
-
API route testing: For testing API routes, you can use supertest.
npm install --save-dev supertest
Example:
import request from 'supertest'; import app from './pages/api/hello'; describe('GET /api/hello', () => { it('should return a 200 status code', async () => { const response = await request(app).get('/api/hello'); expect(response.status).toBe(200); }); });
-
End-to-end testing: Use Cypress for testing full user interactions.
npm install --save-dev cypress
Example:
describe('Home Page', () => { it('should load correctly', () => { cy.visit('/'); cy.contains('Welcome'); }); });
73. What is the difference between a Single Page Application (SPA) and a Next.js app?
- SPA (Single Page Application): In SPAs, the entire application loads as a single HTML page, and JavaScript handles routing and rendering. The page does not reload when navigating between routes, making the user experience faster but slower to initially load.
- Next.js app: Next.js combines the benefits of both SSR and CSR. It allows for hybrid rendering, where pages can be statically generated (SSG), server-side rendered (SSR), or client-side rendered (CSR) based on the use case. This means Next.js apps can offer faster initial page loads compared to SPAs.
74. Why did Next.js introduce the App Router?
The App Router was introduced to enhance flexibility and simplify routing. With the App Router, Next.js allows for better structure and customization in large-scale applications. The App Router provides better support for advanced routing features like layouts, nested routing, and more.
75. How does routing work in the App Router vs. the Pages Router?
-
App Router: The App Router introduces a new approach where you define routing within the
app/
directory, allowing for dynamic and nested routing with layouts and file-based API routes. This approach simplifies handling routes at different levels of your application, including nested and parallel routes. -
Pages Router: The Pages Router uses the
pages/
directory where each file corresponds to a route. It follows a flat structure and doesn't support as much flexibility in routing as the App Router.
76. What is the new app
directory, and how is it different from the pages
directory?
The app/
directory is used with the App Router in Next.js 13 and later. It allows for more flexible routing, including support for layouts, nested routing, and parallel routes. The pages/ directory is used for the older Pages Router, where routes are defined directly by the file structure.
77. How does file-based routing in the App Router enhance Next.jsβs functionality?
File-based routing in the App Router allows for:
- Dynamic routing: Using folders and files for route definitions, Next.js can automatically handle dynamic routes based on the directory structure.
-
Nested routes: Nested files and folders in the
app/
directory enable advanced routing patterns like nested layouts and sub-routes. - Layouts: You can create shared layouts for specific sections of your app, improving reusability and modularity.
78. When would you choose to use a Server Component over a Client Component, and vice versa?
In Next.js, Server Components and Client Components serve different purposes, and choosing between them depends on the use case:
-
Use Server Components when:
- Static rendering: You want to perform server-side rendering (SSR) for the component, allowing it to be rendered on the server and sent to the client as HTML. This can be beneficial for SEO and faster initial load times.
- Heavy logic: The component requires accessing databases, making API calls, or performing other resource-heavy operations that should be done on the server to avoid burdening the client.
- Performance: You can offload rendering and data fetching to the server, reducing the JavaScript bundle size sent to the client, thus improving performance.
-
Use Client Components when:
- Interactivity: The component requires interactivity, such as handling user input, managing state, or triggering side effects (like animations or event listeners) that need to run in the browser.
-
Browser-specific APIs: You need to use browser-specific APIs (e.g.,
window
,localStorage
,document
), which are not available in a server environment. - Dynamic updates: The component needs to react to state changes or props that change dynamically, such as in interactive forms or data visualizations.
79. How do you declare a component as a Client Component in Next.js?
In the App Router of Next.js, a component can be declared as a Client Component by using the 'use client'
directive. This directive must be placed at the top of the file, before any imports or code, to indicate that the component should be treated as a Client Component.
Example:
'use client';
import { useState } from 'react';
function ClientComponent() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default ClientComponent;
80. What are the benefits of using Server Components in terms of performance and scalability?
Server Components offer several benefits related to performance and scalability:
- Reduced JavaScript bundle size: Since Server Components render on the server, they donβt require JavaScript to be sent to the client for rendering. This reduces the JavaScript bundle size and leads to faster page loads.
- Faster initial page loads: By offloading rendering to the server, the HTML is sent directly to the client, resulting in faster time-to-first-byte (TTFB) and faster initial rendering, especially on slower networks or devices.
- Improved SEO: Server Components are rendered server-side, so search engines can crawl the fully rendered HTML, improving SEO compared to client-side rendered content.
- Offloading work from the client: Complex computations, API calls, or database queries are handled on the server, reducing the client's workload and resource consumption, especially for resource-constrained devices like mobile phones.
- Scalability: Since the server handles rendering, applications with many users can scale better by optimizing server-side resources rather than client-side processing. Server-side rendering helps maintain fast load times even as user traffic increases.
Top comments (0)