Search code examples
typescriptnext.jstypescript-typingsgoogle-analytics-4

When I push nextjs code to vercel with google analytics added by @next/third-parties it's showing the following error but it works in development mode


I have recently built a next.js project where I added Google Analytics from @next/third-parties/google. It's working fine in development mode but when I am deploying on vercel.com it's showing the following error.

     ` ./app/layout.tsx:34:24
      Type error: Type 'string | undefined' is not assignable 
      to type 'string'.
      Type 'undefined' is not assignable to type 'string'.
      </NextAuthProvider>
   </body>
   <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS} />
                    ^
  </html>
);
}
  Error: Command "npx prisma generate && next build" exited with 
  1``your text```

Solution

  • Well, at runtime, there is no TS type checking, so nothing will break except that GoogleAnalytics may not work if the gaId is undefined! If you don't have any type errors in your editor, it's possible that the editor isn't using the tsconfig configuration of the project.

    But about the main issue, you can simply cast the type of process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS to string, e.g:

    <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS as string} />
    

    Or just define the types of the environment variables in a type declaration file, e.g:

    src/env.d.ts:

    namespace NodeJS {
      interface ProcessEnv {
        NEXT_PUBLIC_GOOGLE_ANALYTICS: string;
      }
    }
    

    By the way, consider validating environment variables. I suggest using Zod.