Google News
logo
Next.js Interview Questions
Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with Server-side Rendering or Static Generation, and updating or creating content at runtime with Incremental Static Regeneration.
Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when the content of your pages needs to update frequently. Unlike the server-side rendering APIs, you can use client-side data fetching at the component level.
 
If done at the page level, the data is fetched at runtime, and the content of the page is updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the content of the component is updated as the data changes.
 
It's important to note that using client-side data fetching can affect the performance of your application and the load speed of your pages. This is because the data fetching is done at the time of the component or pages mount, and the data is not cached.
The team behind Next.js has created a React hook library for data fetching called SWR (stale-while-revalidate). It is highly recommended if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more.
 
Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us and will revalidate the data if it becomes stale.
import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then((res) => res.json())

function Profile() {
  const { data, error } = useSWR('/api/profile-data', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.bio}</p>
    </div>
  )
}
 
If you export a function called getServerSideProps (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.
export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

When does getServerSideProps run : getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps, then:

When you request this page directly, getServerSideProps runs at request time, and this page will be pre-rendered with the returned props

When you request this page on client-side page transitions through next/link or next/router, Next.js sends an API request to the server, which runs getServerSideProps

getServerSideProps returns JSON which will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have getServerSideProps defined.

You can use the next-code-elimination tool to verify what Next.js eliminates from the client-side bundle.

getServerSideProps can only be exported from a page. You can’t export it from non-page files.

Note that you must export getServerSideProps as a standalone function — it will not work if you add getServerSideProps as a property of the page component.

If you export a function called getStaticProps (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.
export async function getStaticProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

 

You should use getStaticProps if :
 
* The data required to render the page is available at build time ahead of a user’s request

* The data comes from a headless CMS

* The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance

* The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Middleware to rewrite the path.
The Next.js Image component, next/image, is an extension of the HTML <img> element, evolved for the modern web. It includes a variety of built-in performance optimizations to help you achieve good Core Web Vitals. These scores are an important measurement of user experience on your website, and are factored into Google's search rankings.
 
Some of the optimizations built into the Image component include :
 
* Improved Performance : Always serve correctly sized image for each device, using modern image formats

* Visual Stability :
Prevent Cumulative Layout Shift automatically

* Faster Page Loads :
Images are only loaded when they enter the viewport, with optional blur-up placeholders

* Asset Flexibility :
On-demand image resizing, even for images stored on remote servers
Next.js comes with built-in support for environment variables, which allows you to do the following:
 
* Use .env.local to load environment variables
* Expose environment variables to the browser by prefixing with NEXT_PUBLIC_

Default Environment Variables : In general only one .env.local file is needed. However, sometimes you might want to add some defaults for the development (next dev) or production (next start) environment.
 
Next.js allows you to set defaults in .env (all environments), .env.development (development environment), and .env.production (production environment).
 
.env.local always overrides the defaults set.
When a file is added to the pages directory, it's automatically available as a route.
 
The files inside the pages directory can be used to define most common patterns.
 
Index routes : The router will automatically route files named index to the root of the directory.
 
* pages/index.js/
* pages/blog/index.js/blog

Nested routes : The router supports nested files. If you create a nested folder structure, files will automatically be routed in the same way still.
 
* pages/blog/first-post.js/blog/first-post
* pages/dashboard/settings/username.js/dashboard/settings/username

Dynamic route segments : To match a dynamic segment, you can use the bracket syntax. This allows you to match named parameters.
 
* pages/blog/[slug].js/blog/:slug (/blog/hello-world)
* pages/[username]/settings.js/:username/settings (/foo/settings)
* pages/post/[...all].js/post/* (/post/2020/id/title)
Next.js can be deployed to any hosting provider that supports Docker containers. You can use this approach when deploying to container orchestrators such as Kubernetes or HashiCorp Nomad, or when running inside a single node in any cloud provider.
 
* Install Docker on your machine
* Clone the with-docker example
* Build your container: docker build -t nextjs-docker .
* Run your container: docker run -p 3000:3000 nextjs-docker

If you need to use different Environment Variables across multiple environments, check out our with-docker-multi-env example.