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

pages/_app.js (or _app.tsx) is the Pages Router component that wraps every page. Use it for global CSS, context providers, persistent layouts and per-page layout patterns. The App Router replaces it with the root app/layout.tsx.

What it does

Next.js renders _app with two props: Component (the active page) and pageProps (data from getStaticProps/getServerSideProps). Whatever you wrap around <Component {...pageProps} /> applies to every page.

Common uses

  • Global CSS. In the Pages Router, global stylesheets can only be imported in _app.
  • Providers. Theme, auth session, React Query or Redux providers.
  • Persistent layout. UI that should not remount between page changes.
  • Per-page layouts. A getLayout function on each page lets pages opt into different layouts.
  • Analytics or reportWebVitals.

What to avoid

  • Adding getInitialProps to _app disables Automatic Static Optimization for every page, so all pages become server-rendered.
  • Fetching data here for all pages; it runs on every navigation.

App Router equivalent

  • app/layout.tsx is the root layout and must render <html> and <body>.
  • Global CSS is imported there.
  • Providers go in a small Client Component (for example app/providers.tsx) rendered by the layout.
  • Nested layout.tsx files replace the getLayout pattern.

Code example

tsx
1// pages/_app.tsx
2import "@/styles/globals.css";
3import type { AppProps } from "next/app";
4import type { NextPage } from "next";
5import type { ReactElement, ReactNode } from "react";
6import { ThemeProvider } from "@/components/theme";
7
8export type NextPageWithLayout = NextPage & {
9 getLayout?: (page: ReactElement) => ReactNode;
10};
11
12type Props = AppProps & { Component: NextPageWithLayout };
13
14export default function MyApp({ Component, pageProps }: Props) {
15 // Each page can choose its own layout; default is no extra wrapper
16 const getLayout = Component.getLayout ?? ((page) => page);
17
18 return <ThemeProvider>{getLayout(<Component {...pageProps} />)}</ThemeProvider>;
19}
20
21// App Router equivalent: app/layout.tsx
22// export default function RootLayout({ children }: { children: React.ReactNode }) {
23// return <html lang="en"><body><Providers>{children}</Providers></body></html>;
24// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app