DeployU
Interviews / Frontend Engineering / What is the `_app.js` file and what is it used for in Next.js?

What is the `_app.js` file and what is it used for in Next.js?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new Next.js application and you want to add a global stylesheet that will be applied to the entire application.

You are not sure where to put the global stylesheet.

The Challenge

Explain what the _app.js file is in Next.js and how you would use it to solve this problem. What are the key benefits of using the _app.js file?

Wrong Approach

A junior engineer might not be aware of the `_app.js` file. They might try to solve this problem by adding a `<link>` tag to each page, which would not be a very good solution.

Right Approach

A senior engineer would know that the `_app.js` file is the perfect tool for this job. They would be able to explain what the `_app.js` file is and how to use it to add a global stylesheet to the application.

Step 1: Understand What the _app.js File Is

The pages/_app.js file is a special file in Next.js that allows you to override the default App component.

Step 2: The Key Use Cases for the _app.js File

Use CaseDescription
Global StylesTo add a global stylesheet that will be applied to the entire application.
LayoutsTo create a layout that will be shared across all the pages in the application.
State ManagementTo wrap the application in a state management library, such as Redux or MobX.
Error HandlingTo add a global error boundary to the application.

Step 3: Solve the Problem

Here’s how we can use the _app.js file to add a global stylesheet to our application:

// pages/_app.js
import '../styles.css'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

In this example, we import the global stylesheet in the _app.js file. This will cause the stylesheet to be applied to every page in the application.

Practice Question

You want to create a layout that will be shared across all the pages in your application. Which of the following would you use?