Warning: You have opted-out of Automatic Static Optimization due to getInitialProps in…
- User
Warning: You have opted-out of Automatic Static Optimization due to
getInitialPropsinpages/_app. This does not opt-out pages withgetStaticPropshow to fix build
- Assistant
The warning you're experiencing in Next.js is related to using
getInitialPropsin yourpages/_appfile.getInitialPropsdisables Automatic Static Optimization, as it requires server-side rendering (SSR) to resolve the data fetched on the server.Here's how to fix the warning and troubleshoot your build:
1. Migrate
getInitialPropstogetStaticPropsorgetServerSidePropsFirst, determine whether you really need
getInitialPropsin_app. If you're adding functionality like fetching global data (e.g., authentication tokens or layout information), try to refactor it to usegetStaticPropsorgetServerSidePropsin individual pages rather than_app.If you're using it to fetch some dynamic data, here’s what you should do:
A. If Data is Static at Build Time:
Replace
getInitialPropswithgetStaticPropsin individual pages or components where that data is needed.getStaticPropsallows for the page to be statically optimized.// Example for an individual page export async function getStaticProps() { const data = await fetchSomeData(); // Fetch static data at build time return { props: { data }, // Pass as props to your page }; }B. If Data is Dynamic and Needs to Be Fetched Per Request:
Use
getServerSidePropsin individual pages. This allows you to fetch data on every request and keeps server-side behavior localized to specific pages.// Example for a page export async function getServerSideProps(context) { const data = await fetchSomeData(); // Fetch data dynamically per request return { props: { data }, // Pass data to your page }; }Note: Avoid using
getInitialPropsin_appunless absolutely required, as it forces all pages to disable optimization.If you’ve been fetching global data (e.g., authentication), you can also use custom React hooks (e.g.,
useEffect) or Context APIs instead of usinggetInitialProps.
2. If You Must Use
getInitialPropsin_appIf you decide to keep
getInitialPropsin_app, understand that it cannot be combined withgetStaticProps, and you’ll disable static optimization for your app. In this case, you have to ensure your logic is correct.Here’s an example of
getInitialPropsin_app:// pages/_app.js import App from 'next/app'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } // Example: getInitialProps in _app MyApp.getInitialProps = async (appContext) => { // Fetching your global data const appProps = await App.getInitialProps(appContext); return { ...appProps }; }; export default MyApp;This will work, but it will always force SSR for every page, which may be unnecessary.
3. Alternate Solutions: Context APIs or Middleware
If you’re fetching global data like authentication tokens or user sessions, explore using React Context APIs or Next.js Middleware instead. These approaches are often better for handling global state without disabling static optimizations.
Checklist for Fixing the Build:
- Remove
getInitialPropsfrom_app.jsunless absolutely necessary. - Replace it with
getStaticPropsorgetServerSidePropsin individual pages as needed. - If global data fetching is required:
- Explore Context APIs or React hooks (for client-side fetching).
- Use Middleware for server-side logic.
By refactoring as described above, your build should work correctly, and the warning about static optimization will be resolved.
- Remove
- User
MyApp.getInitialProps = async (appContext: AppContext) => { 133 // browser context, rare situation (404 page for instance) 134 if (typeof window !== 'undefined') { 135 const device = deviceDetector(window.navigator.userAgent); 136 const [appProps, { data: platform }] = await Promise.all([ 137 App.getInitialProps(appContext), 138 api.get('platform'), 139 ]); 140 return { ...appProps, platform, device }; 141 } 142 143 // server context 144 const req = appContext.ctx.req; 145 if (!req) return { notFound: true }; 146 const device = deviceDetector(req.headers['user-agent'] || ''); 147 // calls page's
getInitialPropsand fillsappProps.pageProps148 // also get platform, use Promise.all for parallel queries to speed up page load 149 const [appProps, platformResult] = await Promise.all([ 150 App.getInitialProps(appContext), 151 getPlatform(req), 152 ]); 153 154 if ('notFound' in platformResult) { 155 return platformResult; 156 } 157 158 const date = await getFromMemcached( 159 //${platformResult.platform.domain}:${SlugEnum.all_header_before}160${platformResult.platform.domain}:${SlugEnum.all_header_before}, 161 ); 162 163 return { 164 ...appProps, 165 platform: platformResult.platform, 166 device, 167 bannersHeight: { 168 [SlugEnum.all_header_before]: date 169 ? Math.abs(differenceInMinutes(new Date(), new Date(date))) < 1 && 170 '200px' 171 : '0', 172 }, 173 }; src/pages/_app.tsxhere's mine app.tsx, is it possible to fix?
- Assistant
Looking at the code you've posted, it is clear that your
_app.tsxusesgetInitialProps. This forces the app to fall back to server-side rendering (SSR) for all pages, which disables Automatic Static Optimization.Let's break this down and explore how you could potentially refactor it or work around it to regain optimizations without compromising your functionality.
Observations in Your Code
-
Device Detection:
- You are detecting the device (based on the
user-agent) either on the server (req.headers['user-agent']) or client-side (window.navigator.userAgent). This is used to determine certain platform/device-specific properties.
- You are detecting the device (based on the
-
Global API Calls:
- You're making API calls and retrieving platform data (
api.get()on the client orgetPlatform()on the server). - You're fetching banners height and caching the result from
memcached.
- You're making API calls and retrieving platform data (
-
Client vs. Server Context Handling:
- There's a split logic depending on whether the app is running in the browser or on the server.
Why This Breaks Static Optimization
Next.js disables Automatic Static Optimization when
MyApp.getInitialPropsis implemented in_app.tsx. This happens because:- Static optimization requires a clear separation of
getStaticPropsandgetServerSidePropsfor fetching data on a per-page basis. - Using
getInitialPropshere essentially forces all pages to SSR, impacting performance.
However, given that your
_app.tsxfetches global data (e.g.,platform), it is still possible to refactor this setup.
Possible Refactor or Fix
To fix this issue, you can move the fetching logic to individual pages or reusable helpers (if possible) and replace
getInitialPropswith solutions likegetServerSideProps,getStaticProps, or React Context.
Steps to Refactor
-
Refactor API Calls Move the platform and
bannersHeightfetching logic to page-levelgetServerSidePropsoruseEffecthooks instead of_app.tsx. This is because_app.tsxshouldn't handle page-specific data.Example
getServerSidePropsin a page:// Example Page import { deviceDetector } from '../utils/deviceDetector'; import { getPlatform, getFromMemcached } from '../utils/api'; export const getServerSideProps = async (context) => { const req = context.req; const device = deviceDetector(req.headers['user-agent'] || ''); const platformResult = await getPlatform(req); if (!platformResult) { return { notFound: true, }; } const date = await getFromMemcached( `${platformResult.platform.domain}:${SlugEnum.all_header_before}`, ); const bannersHeight = { [SlugEnum.all_header_before]: date ? Math.abs(differenceInMinutes(new Date(), new Date(date))) < 1 && '200px' : '0', }; return { props: { platform: platformResult, device, bannersHeight, }, }; }; const Page = ({ platform, device, bannersHeight }) => { return ( <div> <h1>Platform: {platform.name}</h1> <p>Device: {device.type}</p> <div style={{ height: bannersHeight[SlugEnum.all_header_before] }} /> </div> ); }; export default Page; -
Device Detection on the Client If the
devicedetection logic is required at the app level (e.g., for all the pages), move thedeviceDetectorlogic to a custom React hook or useuseEffectto detect it client-side._app.tsxexample with client detection:import { useState, useEffect } from 'react'; import type { AppProps } from 'next/app'; import { deviceDetector } from '../utils/deviceDetector'; const MyApp = ({ Component, pageProps }: AppProps) => { const [device, setDevice] = useState(null); useEffect(() => { const detectedDevice = deviceDetector(window.navigator.userAgent); setDevice(detectedDevice); }, []); return <Component {...pageProps} device={device} />; }; export default MyApp;This way, device detection is performed only in the client environment.
-
Platform Data Using Middleware If the
platformandbannersHeightare global and required for every single request, consider using Next.js Middleware.The middleware can handle server-side logic like fetching
platformanddevice, then attach the data to the request or response headers. This keeps_app.tsxlight.Example
middleware.ts:import { NextRequest, NextResponse } from 'next/server'; import { getPlatform } from './utils/api'; export async function middleware(req: NextRequest) { // Detect the device const userAgent = req.headers.get('user-agent'); const device = userAgent ? deviceDetector(userAgent) : 'unknown'; // Fetch platform const platformResult = await getPlatform(req); if (!platformResult) { return NextResponse.redirect('/404'); } // Add data to the request headers for downstream processing req.headers.set('x-device', JSON.stringify(device)); req.headers.set('x-platform', JSON.stringify(platformResult.platform)); return NextResponse.next(); }Then access this data in
getServerSidePropsby readingreqheaders. -
Remove
getInitialPropsfrom_app.tsxOnce these changes are applied,_app.tsxno longer needsgetInitialProps. Focus on using Context, hooks, or passing props viagetServerSidePropsorgetStaticProps.Example simplified
_app.tsx:import type { AppProps } from 'next/app'; const MyApp = ({ Component, pageProps }: AppProps) => { return <Component {...pageProps} />; }; export default MyApp;This refactoring resolves the root issue because
_app.tsxno longer forces SSR.
Summary of Key Points
-
Check if Global Data Can Be Refactored:
- Move page-specific data fetching (e.g.,
bannersHeight,platform) intogetServerSidePropsorgetStaticProps.
- Move page-specific data fetching (e.g.,
-
Device Detection:
- Perform on the client if possible using hooks (
useEffect). - For server-side device detection, use Middleware or attach the device detection logic to individual pages.
- Perform on the client if possible using hooks (
-
When to Use Middleware:
- If certain global properties are required everywhere, handle them in Middleware to decouple logic from
_app.tsx.
- If certain global properties are required everywhere, handle them in Middleware to decouple logic from
-
Remove
getInitialPropsfrom_app.tsx:- Replace it with simpler logic (or just omit it).
By following this, you'll make your app more modular, maintain static optimizations, and improve performance! Let me know if you need further clarification or examples.
-