Next.js is a powerful React framework that simplifies the development of production-ready web applications by providing features like server-side rendering (SSR), static site generation (SSG), and API routes. Due to its wide adoption in the industry, many companies now include Next.js-specific questions in their interviews. In this blog, we’ll cover some of the most challenging Next.js interview questions and provide detailed answers to help you succeed.
1. What are the key differences between server-side rendering (SSR) and static site generation (SSG) in Next.js?
Answer:
- Server-Side Rendering (SSR): In SSR, the HTML is generated on each request at runtime, and the server responds with the fully rendered HTML. SSR is ideal for pages that need to display frequently updated or dynamic data.
- Static Site Generation (SSG): In SSG, the HTML is generated at build time and reused for each request. SSG is ideal for content that doesn’t change often, as it reduces the server load by serving pre-rendered pages.
SSR Example:
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }, // Passed to the page component as props
};
}
SSG Example:
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }, // Passed to the page component as props
};
}
Explanation: SSR fetches data on each request, while SSG fetches data at build time and serves the pre-rendered page, improving performance.
2. What is the difference between getServerSideProps
and getStaticProps
in Next.js?
Answer:
getServerSideProps
: Runs on the server during each request. It is used when you need to fetch data on every request. This method enables server-side rendering (SSR).getStaticProps
: Runs at build time and generates a static page. It is used when the data is static or infrequently updated, enabling static site generation (SSG).
Example of getServerSideProps
:
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
Example of getStaticProps
:
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
Explanation: getServerSideProps
is called on each request, while getStaticProps
is called at build time.
3. How does Next.js handle dynamic routing?
Answer:
Next.js allows you to create dynamic routes by using square brackets []
in the file names inside the pages/
directory. These brackets act as placeholders for dynamic parts of the URL.
Example:
- File:
pages/product/[id].js
In the example above, id
is the dynamic part of the URL.
Usage:
import { useRouter } from 'next/router';
const ProductPage = () => {
const router = useRouter();
const { id } = router.query;
return <div>Product ID: {id}</div>;
};
export default ProductPage;
Explanation: Dynamic routing in Next.js makes it easy to handle pages that have dynamic URLs, such as product or user profile pages.
4. What is Incremental Static Regeneration (ISR) in Next.js?
Answer:
Incremental Static Regeneration (ISR) allows you to update static content after it has been generated at build time. With ISR, you can specify a revalidate
interval, and Next.js will regenerate the static page on the server when a request comes in after the specified interval.
Example:
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data },
revalidate: 10, // Re-generate the page every 10 seconds
};
}
Explanation: ISR enables you to combine the best of SSG and SSR, where static pages are pre-rendered but can still be updated dynamically at specific intervals.
5. How does Next.js handle API routes?
Answer:
Next.js allows you to create API routes by placing files inside the pages/api/
directory. Each file in this directory maps to an API endpoint.
Example:
- File:
pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello World' });
}
Explanation: In this example, when you access /api/hello
, it will return a JSON response with { message: 'Hello World' }
.
6. What is the getInitialProps
method, and how is it different from getServerSideProps
and getStaticProps
?
Answer:
getInitialProps
is a method used in Next.js for both server-side and client-side data fetching, primarily in older Next.js versions. It can be used in both pages and custom App components, but it is now mostly replaced by getServerSideProps
and getStaticProps
.
getServerSideProps
: Fetches data on the server-side on each request.getStaticProps
: Fetches data at build time.getInitialProps
: Fetches data either on the server-side or client-side, depending on how the page is rendered.
Example:
class MyPage extends React.Component {
static async getInitialProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { data };
}
render() {
return <div>{this.props.data}</div>;
}
}
Explanation: getInitialProps
can still be used but is less efficient than getStaticProps
and getServerSideProps
due to its dual rendering behavior.
7. What is the use of _app.js
in Next.js?
Answer:
The _app.js
file allows you to override the default App component in Next.js. It’s used for setting up things that should be shared across all pages, like layouts, global styles, and custom error handling.
Example:
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
Explanation: The _app.js
component wraps all page components, making it a great place for global configurations like Redux providers or custom layouts.
8. How does next/link
optimize navigation in Next.js?
Answer:
The next/link
component is used to enable client-side navigation between pages in Next.js. It prefetches linked pages in the background to optimize performance by making the page transitions faster.
Example:
import Link from 'next/link';
function HomePage() {
return (
<div>
<Link href="/about">
<a>Go to About Page</a>
</Link>
</div>
);
}
export default HomePage;
Explanation: The Link
component improves performance by prefetching linked pages, reducing loading times during navigation.
9. What is the difference between next/image
and a regular HTML <img>
tag?
Answer:
The next/image
component in Next.js provides an optimized way to serve images. It automatically handles image loading, resizing, and lazy loading, improving performance and user experience.
Example:
import Image from 'next/image';
function MyComponent() {
return <Image src="/path/to/image.jpg" width={500} height={300} alt="Image" />;
}
Explanation:
next/image
: Automatically optimizes images for different screen sizes, formats, and lazy loads images.- Regular
<img>
: Loads images immediately without optimization, affecting performance.
10. What is the purpose of next.config.js
in Next.js?
Answer:
The next.config.js
file is used to configure various settings for a Next.js application, such as environment variables, custom webpack configurations, redirects, rewrites, and more.
Example:
module.exports = {
reactStrictMode: true,
images: {
domains: ['example.com'],
},
};
Explanation: The next.config.js
file gives you control over Next.js behavior, enabling custom configurations for builds, server-side settings, and optimizations.
Conclusion
Next.js offers powerful features like SSR, SSG, API routes, and image optimization, making it a popular framework for building modern
web applications. By understanding the intricacies of these topics, you’ll be well-prepared to tackle even the toughest Next.js interview questions.
Good luck with your interviews!