Hiprup

What is the _app.js (or _app.tsx) file used for in Next.js?

_app.tsx is the top-level component in the Pages Router. Every page in your app is rendered through it, so it's the place to set up things that need to apply to every route — global styles, providers, layouts, error tracking, analytics.

The default version Next.js generates:

// pages/_app.tsx
import type { AppProps } from 'next/app';
import '../styles/globals.css';

export default function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

Component is the active page; pageProps are the props returned from getStaticProps / getServerSideProps.

What it's typically used for:

  • Global CSS — global stylesheets must be imported here, not in individual pages.

  • Context providers — wrap the app in providers for auth, theme, React Query, Redux, etc., so every page has access.

  • Persistent layouts — render headers, sidebars, or chrome that shouldn't unmount on navigation.

  • Error boundaries and analytics — top-level monitoring that fires on every page view.

  • Per-page layouts — by reading a static getLayout property off the page component, you can apply different shells without re-mounting.

A real-world example:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'next-themes';

const queryClient = new QueryClient();

export default function App({ Component, pageProps }: AppProps) {
  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider>
        <Component {...pageProps} />
      </ThemeProvider>
    </QueryClientProvider>
  );
}

In the App Router, _app.tsx doesn't exist. Its responsibilities split across:

  • app/layout.tsx — the root layout, which renders <html> and <body> and wraps every page. Global CSS is imported here.

  • Nested layouts — any folder can have its own layout.tsx that wraps its routes, giving you persistent UI without the getLayout trick.

  • Client providers — pulled into a small client component (often app/providers.tsx) and rendered inside the root layout.

If you're starting a new project, use the App Router — it's where all new framework features land. _app.tsx is for older projects still on the Pages Router.

Explain that _app.js is Pages Router-specific and is replaced by layout.tsx in the App Router. This shows you understand both systems and the migration path.

Mention the key use case: wrapping the app in providers.

What is the _app.js (or _app.tsx) file used for in Next.js? | Hiprup